Python if ... else Statement

The if ... else statement executes a group of statements when a condition is True; otherwise, it will execute another group of statements.

The syntax of if ... else statement is given below:

if condition: 
	statements1 
else: 
	statements2
							
							

Flowchart of Python if... else Statement

Python if ... else Statement
x=5
if x> 0: 
print(x, " is positive") 
else: 
print(x, " is negative")
							

x = int(input('Enter a number:')) 
if x>=1 and x<=10: 
print("You typed", x, "which is between 1 and 10") 
else: 
print("You typed", x, "which is below 1 or above 10")

							

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example

One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")