python中没有if块的else块

Has*_*Ali 2 python for-loop if-statement control-flow

我在网上找到了Python代码片段来打印素数的范围,但最后一个else块对我来说没有意义,因为它没有相应的if块

注意 else 块的缩进是故意的,因为它可以正常工作,并且我在观看 YouTube 上的教程后想出了此代码:https ://www.youtube.com/watch?v=KdiWcJscO_U

entry_value = int(input("Plese enter the starting value:"))
ending_value = int(input("Plese enter the ending value:"))
for i in range(entry_value, ending_value+1):
    if i>1:
        for j in range(2,i):
            if i%j == 0:
                break
        else:
            print("{} is prime number".format(i))
Run Code Online (Sandbox Code Playgroud)

Big*_*677 6

Python(和其他语言)使用else块来指定仅在for循环完成且不中断时运行的代码。

在您的代码中,if i%j == 0循环将退出,但不会调用 else 代码。

这是一个带有注释的示例:

for x in range(2,i):
    if i%j == 0:
        break #number is not prime so we break and don't call else
else:
    print("{} is prime number".format(i))
Run Code Online (Sandbox Code Playgroud)