15 ms·
It is worth noting that the else clause can also be used with while loops. [1]: https://docs.python.org/3.6/reference/compound_stmts.html#while https://docs.py
by kbumsik 8y ago
It is worth noting that the else clause can also be used with while loops.
[1]: https://docs.python.org/3.6/reference/compound_stmts.html#while https://docs.python.org/3.6/reference/compound_stmts.html#wh...
- kasbah 8y agoSeems 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.
- deleted 8y ago[deleted]
- ubernostrum 8y agoAnd the full form of a Python exception handling block is not try/except/finally. It's try/except/else/finally. The 'try' block contains code which might raise an exception. It can be followed by zero or more 'except' blocks, each of which indicates the type(s) of exception it will catch and contains code to execute in the event of that type of exception. The 'except' block(s) can be followed by one 'else' block, which contains code to execute in the event no exception was raised by the code in the 'try' block. And then there is optionally a 'finally' block, containing code that must be executed in all circumstances.