In the previous tutorials we have seen if statement and if..else statement. In this tutorial, we will learn if elif else statement in Python. The if..elif..else statement is used when we need to check multiple conditions.
Syntax of if elif else statement in Python
This way we are checking multiple conditions.
if condition: block_of_code_1 elif condition_2: block_of_code_2 elif condition_3: block_of_code_3 .. .. .. else: block_of_code_n
Notes:
1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed.
2. Out of all these blocks only one block_of_code gets executed. If the condition is true then the code inside ‘if’ gets executed, if condition is false then the next condition(associated with elif) is evaluated and so on. If none of the conditions is true then the code inside ‘else’ gets executed.
Python – if..elif..else statement example
In this example, we are checking multiple conditions using if..elif..else statement.
num = 1122 if 9 < num < 99: print("Two digit number") elif 99 < num < 999: print("Three digit number") elif 999 < num < 9999: print("Four digit number") else: print("number is <= 9 or >= 9999")
Output:
Leave a Reply