Python If, elif, and else condition
This tutorial is Python If, elif, and else statements. Controlling the flow of the program by making conditions on that basis specific block of code will execute. If the statement is making a condition or decision withing a program in Python.
if Condiction
The condition is true then execute the block of code and otherwise execute the next condition.
Syntax
if condition :
# true statement
next statement
Example
number = 30 if number%2 == 0 : print("Even number") print ("Number is :", number) Output: Even number Number is : 30
if-else condition
If the condition only executes condition returns true if the condition returns false for we use else condition with if.
Syntax
if condition :
# true statement
else:
# false statement
next statement
Example
number = 11 if number%2 == 0 : print("Even number") else : print("Odd number") print("Number is :",number) Output: Odd number Number is : 11
Elif condition
The condition is not true then we check again with other conditions using Elif.
Syntax
if condition:
# true statement1
elif condition:
# true statement2
elif condition:
# true statement3
…
…
else:
# false statement
# next statement
Example
number = 33 if number == 11: print("If first statement") elif number == 22: print("If second statement") elif number == 33: print("If third statement") else: print("Else fourth statement") print("Number is :",number) Output: If third statement Number is : 33
Nesting
Generally, use nested if condition using this we define if condition within another if condition. see the following code below:
Syntax
if condition:
if condition:
# true statement
else:
# false statement
else:
if condition:
# true statement
else:
# false statement
# next statement
Example
number = 55 if number == 11: if number == 55: print ("First statement") else : print ("Second statement") else: if number == 55: print ("Third statement") else : print ("Fourth statement") print("Number is :",number) Output: Third statement Number is : 55