Skip to content

Python if Statements

How to use Python's if, if-else, if-elif, and nested conditional statements to control program flow with proper syntax and indentation.

Python Conditional Statements

Almost in every program it is necessary to execute code only under certain conditions.

To be able to do this, the following conditional statements are available in Python:

  • if
  • if..else
  • Nested if
  • if-elif statements

Python if Statement

The if statement is the simplest conditional instruction: it executes inner block of instructions only if the condition is evaluated True.

Syntaxpython
if condition:

For example:

a = 10
if a > 15:
    print(f"{a} is greater than 15")

a = -1
if a > 15:
    print(f"{a} is greater than 15")
    
print("The end")

Output

10 is greater than 15
The end

Python if-else Statement

The if..else statement evaluates a condition and executes the inner instruction block of if only if the test condition is True. Otherwise, if the condition is False, the inner instruction block of else is executed.

Syntaxpython
if condition:
else:

For example:

a = 10
if a % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Python if-elif-else Statement

elif stands for else if: it allows you to check for multiple expressions.

if condition:
elif condition:
..
..
..
else:
  • If the condition of if is False, check the condition of the next block elif and so on.
  • If all the conditions are False, the inner instruction block of else is executed.

For example:

num = 1.2

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

where:

  • if num is positive, Positive number is printed.
  • If num is equal to 0, Zero is printed.
  • If num is negative, Negative number is printed.

Python Nested If

if...elif...else statement can be nested inside another if...elif...else statement.

if condition1:
    if condition2:

For example:

num = int(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

And some output with different numbers:

Enter a number: 10
Positive number
Enter a number: 0
Zero
Enter a number: -5
Negative number

Shorthand if and if-else

Shorthand if and if-else are if statements that are written on the same line as the if statement.

They are known as Conditional Expressions (or Ternary Operators) and are discussed in detail in the dedicated chapter.

if a > b: print("a is greater than b")

a = 1
b = 10
print("a") if a > b else print("b")
Navigation