+ 1
Hi , i am not able to understand this code to tell the output please help me out
try: print(1) print(1 + "1" == 2) print(2) except TypeError: print(3) else: print(4)
2 Answers
+ 4
Hi Sahana!
In a try-else statement, else part is executed if there is no error occurred in try statement. Otherwise, the error is caught in except part. That's the thing you have to consider when you're using try-except-else statement. Here, second print statement is wrong. That's why it's giving output 1, 3.
+ 2
1 is printed first, as there was no error prior to printing 1. The command "print(1 + '1' == 2)" would throw an TypeError, because you can't add an integer to a string. However, you catch the error in the "except" block, which just prints 3 if a TypeError arises. The else block isn't used in this case.