Python if…else Statement Explained

The if-else statement in Python is used to make decisions based on certain conditions. It allows your program to execute different blocks of code depending on whether a condition is true or false.

python if else statement explained with examples

Syntax

if condition:
    # Code to execute if condition is True
else:
# Code to execute if condition is False

Here, condition is a boolean expression that evaluates to either True or False. If the condition is True, the code inside the if block is executed. If the condition is False, the code inside the else block is executed.

Simple if…else Statement

Example:

x = 5

if x > 10:
    print("x is greater than 10")
else:
print("x is less than or equal to 10")

Ouput:

x is less than or equal to 10

if…else with Multiple Conditions

You can add multiple elif (short for “else if“) statements to check additional conditions if the initial condition is False.

Example:

age = 20

if age < 18:
    print("You are a minor")
elif age >= 18 and age < 65:
    print("You are an adult")
else:
print("You are a senior citizen")

Output:

You are an adult

Nested if…else Statements

You can nest if...else statements inside each other to create more complex decision-making structures.

Example:

x = 5
y = 10

if x > 0:
    if y < 20:
        print("Both conditions are True")
    else:
        print("y is greater than or equal to 20")
else:
print("x is less than or equal to 0")

Output:

Both conditions are True

Ternary if…else (Conditional Expression)

You can also use a ternary if...else expression for shorter conditional assignments.

x = 5
even_or_odd = "even" if x % 2 == 0 else "odd"
print(even_or_odd)  # Output: "odd"

Using if…else in List

if...else can be used within list comprehensions to conditionally include items in a list.

numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0 else num * 2]
print(even_numbers)  # Output: [2, 4, 6, 8, 5]

Using if…else in Dictionary

Similar to list comprehensions, you can use if...else in dictionary comprehensions.

grades = {'Alice': 85, 'Bob': 70, 'Charlie': 95}
result = {name: 'Pass' if score >= 70 else 'Fail' for name, score in grades.items()}
print(result)  # Output: {'Alice': 'Pass', 'Bob': 'Pass', 'Charlie': 'Pass'}