0
Else Statements and Exception Handling
Hi, I have been having trouble understanding how this code works: for i in range(10): try: if 10 / i == 2.0: break except ZeroDivisionError: print(1) else: print(2)
4 Antworten
+ 2
If the else belongs to the for loop:
The else statement will be run when the for loop statement terminates, unless the for loop was terminated by the break statement, like it will.
+ 2
If the else belongs to the try-except statement:
The else statement will be run when an error does not appear in the try-except statement.
+ 1
Does that else statement belong to the for loop or to the try-except statement?
+ 1
Range of 10 is producing 10 numbers from 0 to 9 so the result of this is going to be - 1 2 2 2
The else statement after the try/except is used to execute code when there is no exception and to not when exception is handled by the except clause.