try-except vs if-else in Python with examples
In this tutorial, we are going to compare the try-except block with if-else statements in Python and see how they can be used in our Program. As we know, if-else statements are used with conditional statements. They can be used to select a set of statements to be executed based on a condition. We can also use a try-except pair for the same. Let’s see an example.
code1 = """ x = 5 if x: print("x = ",x) else: print("Oh No!") """ code2 = """ x = 5 try: print("x = ",x) except: print("Oh No!") """ print("Executing code1....") exec(code1) print("Executing code2") exec(code2)
Output:
Executing code1.... x = 5 Executing code2 x = 5
In the above example program, as you can see we have stored two string of Python code in variables code1 and code2. code1 implements an if-else statement whereas code2 implements a try-except statement. From the output, you can infer that everything went well and we can implement conditional statements using try-except.
Now let’s just make a little change in our program.
code1 = """ x = 5 if x: print("x = ",x) else: print("Oh No!") """ code2 = """ try: print("y = ",y) except NameError: print("Oh No!") """ print("Executing code1....") exec(code1) print("Executing code2") exec(code2)
Output:
Executing code1.... x = 5 Executing code2 Oh No!
As you can see, here, we have not provided the value of y in the try-except block the code catches the NameError exception and prints the statements in except block. If we do not provide the value of x in if-else code, then NameError exception will be thrown. Therefore, the use of try-except is encouraged when there is a possibility of error or exceptions.
Now that we know how we can use the try-except block as a replacement of if-else, let us see which one works faster. Have a look at the below Python program.
import timeit code1 = """ x = 5 if x: print("x = ",x) else: print("Oh No!") """ code2 = """ x = 5 try: print("x = ",x) except: print("Oh No!") """ codes = [code1, code2] for code in codes: time_taken = timeit.timeit(stmt = code,number = 1) print(time_taken)
Output:
x = 5 0.00023400000000000504 x = 5 0.00013280000000000236
It is evident from the output that the try-except statement takes less time than an if-else statement.
Thank you.
Also read: Understanding timeit in Python
Leave a Reply