for i in range(4):
print("printing inside forloop")
else:
print("printing in else, which shouldn't be")
The else
clause of a for loop runs unless the loop is exited via a break
.
for i in range(4):
print("printing inside for loop")
if i == 3:
break
else:
print("This won't print")
Why do you think this is an error?
Thanks, but
- Does the for-else serve any purpose/use case?
- If it doesn’t close well, perhaps we could use the “if n else” statement only. I expect the interpreter to throw an error: ‘else’ without a previous ‘if’.
because I expect that code (for loop + else) to be interpreted in this way,
while cond True:
# do this
else:
break
else:
print("printing in else, which shouldn't be")
which is now interpreted as
while True:
# do this
else:
print("printing in else, which shouldn't be")
In the context of a for
statement you can pretend that the else
means nobreak
.
1 Like
I forget, once a month, which case the else
block of the for statement and while statement is executed.
The for..else
or while...else
syntax is more difficult than the English phrase “unless otherwise explicitly…”
The nobreak
is useful to remember.