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:

CopiedCopy Code

if condition: 
	statements1 
else: 
	statements2
							
							

if-else flowchart

Python if-else Statement
CopiedCopy Code

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

CopiedCopy Code

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 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:

CopiedCopy Code

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