[Solved] Why is the 'else' part ignored on the second case but not in the first case? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

[Solved] Why is the 'else' part ignored on the second case but not in the first case?

#first print('First:') try: print(1) print('1' + '1') print(3) except TypeError: print(4) else: print(5) #second print('second') try: print(1) print(1 + '1') print(3) except TypeError: print(4) else: print(5)

16th Apr 2020, 7:47 AM
Bibek Oli
Bibek Oli - avatar
3 Answers
+ 1
The statements within the first "try" block do not cause any exception to occur, so the following"except" statement will not be executed. This, the "else"statement will. But in the second "try" statements, the " 1+'1' " causes a TypeError exception, so the "except" statement will be executed. So, the second "else" statement will not be executed. The rules are here: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2487/
16th Apr 2020, 7:59 AM
Gwlanbzh
Gwlanbzh - avatar
0
the else statement is executed only if the 'main' statement, the base statement, exited normally, without a break or any exception.
16th Apr 2020, 7:55 AM
John Robotane
John Robotane - avatar
0
I did not try your code but I assume that the else statement "rather belongs to the except statement than to the try statement". We can think of the except statement as the if part to the else statement. First case: Try succeeds, so no exception. if no exception than else. Second case: Try fails, so exception. If exception, no else.
16th Apr 2020, 8:01 AM
Lisa
Lisa - avatar