+ 1
Break statement
I came across this, need help #codes below for i in range(5): print("for loop") break else: print("else statement") print("last line") This code outputs: for loop last line Can someone explain how break statement breaks from both for loop and else statement
6 Answers
+ 5
else is not executed because of the break statement (because the execution reaches the break statement).
such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.
if you had an
if i % 2 == 0:
print(i)
break
inside the for loop if the condition is never true, and execution doesn't reach the break statement, then the else statement which is outside the for loop will be executed.
if break is not reached the else statement will be executed
+ 5
Namit Jain it is possible to have such a thing in python but it's rarely used, since you can handle everything directly inside the for loop.
what matters there is the break keyword. the else condition will be executed only if the break statement inside the loop is never reached. therefore you need an if statement inside the for loop (only the if statement, without any elif or else). and the break statement should be inside the if statement (at the bottom of the if logic). if that break is never reached, the else outside the for loop is executed. if break is reached, the for loop execution terminates and else is ignored
+ 4
Else is not in the for loop
I think it should show an error.. As your code has else statement without if statement
+ 2
Sebastian Pacurar Thank you. Your explanation makes the confusion clear.
PANKAJ NAIK Thank you too for the reply. I have a clear concept about if and else. My confusion was not as per your code. It was just that even after breaking for loop, the else part was skipped and then the proceeding line was executed. Hope you understand
Thank you all once again
Happy coding
+ 2
Namit Jain Actually i have verified the code. It works perfectly fine. My point was only to show that break statement inside the for loop was skipping the else statement outside the loop.
Thanks for the reply
0
Break statement
Use if condition inside for loop
đđthis will your doubt
for i in range(5):
If i==3:
print("for loop")
break
else:
print("else statement")
print("last line")
đđkeep learning