3 ms·
Seems a bit useless since while x < 2: ... else: print('>= 2') is the same as while x < 2: ... print('>= 2') unles
by kasbah 8y ago
Seems a bit useless since
while x < 2:
...
else:
print('>= 2')
is the same as
while x < 2:
...
print('>= 2')
unless you use a break. Just seems unnecessarily confusing to me. I have used for ... else though.
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- znpy 8y agoI think that the subtle difference is that in the second example "print('>= 2')" is always executed whereas in the first example the print statements is executed only if no break was executed in the while loop. Quoting documentation: "A break statement executed in the first suite terminates the loop without executing the else clause’s suite."
- kasbah 8y agoI did say "unless you use a break". I don't think this is very useful.
- jwilk 8y agoBut... for+else without break can be rewritten the same way. And yet you claim that you've used for+else. But indeed, in my experience, while+else are much less common that for+else. I'm not sure why.