for-else

Why does this `else` block work yet it is not on the same level as the `if` case? [duplicate]

本小妞迷上赌 提交于 2019-12-10 17:48:33
问题 This question already has answers here : Why does python use 'else' after for and while loops? (21 answers) Closed 2 years ago . This code runs pretty well and generates the wanted list of prime numbers. But the else block that prints our prime numbers is out of block, but it works anyway, can someone explain it to me? for num in range(0, 100 + 1): # prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) Reference: programiz.com 回答1:

Why does python use 'else' after for and while loops?

和自甴很熟 提交于 2019-11-26 03:12:51
问题 I understand how this construct works: for i in range(10): print(i) if i == 9: print(\"Too big - I\'m giving up!\") break; else: print(\"Completed successfully\") But I don\'t understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can\'t progress seamlessly from the for statement to the else block. To me, continue or continuewith would