+ 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

29th May 2020, 2:32 PM
BENJAMIN LIMBU SUBBA
BENJAMIN LIMBU SUBBA - avatar
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
29th May 2020, 2:38 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 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
29th May 2020, 2:53 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 4
Else is not in the for loop I think it should show an error.. As your code has else statement without if statement
29th May 2020, 2:35 PM
Namit Jain
Namit Jain - avatar
+ 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
29th May 2020, 3:49 PM
BENJAMIN LIMBU SUBBA
BENJAMIN LIMBU SUBBA - avatar
+ 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
29th May 2020, 3:52 PM
BENJAMIN LIMBU SUBBA
BENJAMIN LIMBU SUBBA - avatar
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
29th May 2020, 3:03 PM
PANKAJ NAIK
PANKAJ NAIK - avatar