Python If…Else Statements
In this tutorial you'll learn how to create a decision structure, using if...else statements in Python.
Like C++ or Java, Python also support to write code that perform different actions based on the results of a logical or comparative conditions.
The if Statement
The if statement is used to write decision-making code, which allows a program to have more than one path of execution.
x = 10 y = 20 if x < y: print("x is less than y")
x is less than y
The if...else Statement
An if-else statement will execute one block of code if its condition is true, or another block of code if its condition is false.
x = 10 y = 5 if x < y: print("x is less than y") else: print("y is less than x")
y is less than x
The if...elif...else Statement
To test more than one conditions, the if...elif...else is a special statement that is used to combine multiple if...else statements.
x = 10 y = 10 z = 15 if x < y: print("x is less than y") elif x < z: print("x is less than z") else: print("x is equal to y")
x is less than z
Short Hand Statements
Short hand provides a great way to write compact if-else statements, if you have only one statement to execute.
x = 10 y = 5 if x > y: print("X") print("X") if x > y else print("Y") print("X") if x > y else print("X == Y") if a == b else print("Y")
X X X