Learn Python Programming

Python If … Else


Python If…else control statement is used to execute one or more statement depending on whether a condition is true or not. If…else control statement is used in decision making statements.

Syntax for correct format of if statement :

if conditions:
	statements

First the condition is checked if it is true then the statements given after colon(:) are executed.

Python if Statement Flowchart: Decision making structure in most programming language

In Python, following logical conditions from mathematics are used:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b Less than or equal to: a <= b Greater than: a > b
  • Greater than or equal to: a >= b

Example: Python if Statement

# To check a number whether it is a positive.
num = 5
if num > 0:
    print(num, "is a positive number.")

#Output:
5 is a positive number.

Elif

The Elif keyword is used when earlier statement becomes false, then statement under Elif executed.

Syntax:

if condition:
		statements1
elif:
		statements2

Example: Python Elif Statement

# To check a number whether it is a positive or negative.
num = -5
if num > 0:
    print(num, "is a positive number.")
elif num < 0:
    print(num, "is a negative number.")

#Output:
-5 is a negative number.

Else

The Else statement is executed when all the earlier conditions becomes false.

Syntax:

if condition:
		statements1
elif:
		statements2
else:
		statements3

Example: Python Else Statement

# To check a number whether it is a greater or smaller or equal to 10.

num = 10
if num > 10:
    print(num, "is a greater than 10.")
elif num < 10:
    print(num, "is a smaller than 10.")
else:
    print(num, "is a equal to 10.")

#Output:
10 is a equal to 10.