If Else in Python

Our first program will demonstrate the usage of if/else statements. Here’s the full source code:

# Here's a basic example
if 7 % 2 == 0:
    print("7 is even")
else:
    print("7 is odd")

# You can have an if statement without an else
if 8 % 4 == 0:
    print("8 is divisible by 4")

# Logical operators like 'and' and 'or' are often useful in conditions
if 8 % 2 == 0 or 7 % 2 == 0:
    print("either 8 or 7 are even")

# A statement can precede conditionals; any variables
# declared in this statement are available in the current
# and all subsequent branches
num = 9
if num < 0:
    print(num, "is negative")
elif num < 10:
    print(num, "has 1 digit")
else:
    print(num, "has multiple digits")

Branching with if and else in Python is straightforward.

You can have an if statement without an else.

Logical operators like and and or are often useful in conditions.

A variable assignment can precede conditionals; any variables declared in this statement are available in the current and all subsequent branches.

Note that you don’t need parentheses around conditions in Python, but that the indentation is required to define the scope of the conditional blocks.

To run the program:

$ python if_else.py
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Python doesn’t have a ternary operator like some other languages, but it does have a concise one-line conditional expression:

result = "even" if num % 2 == 0 else "odd"

This can be used for simple conditions, but for more complex logic, a full if statement is recommended.