Codectionary / Developer documentation / Python

if

The if statement is Python's primary conditional control structure. It allows your program to make decisions by executing different code blocks based on whether a condition is True or False. The if statement is fundamental to creating dynamic, responsive programs that can adapt their behavior based on various conditions, user input, or data states.

Syntax

if condition:
    # code to execute if condition is True

Examples

Basic Conditionals

Simple if statements that execute code when a condition is met.

age = 18

if age >= 18:
    print("You are an adult")

temperature = 30

if temperature > 25:
    print("It's hot outside!")
    print("Remember to stay hydrated")

score = 85

if score >= 60:
    print("You passed!")

If-Else Statements

Using else to handle the alternative case when the condition is False.

password = input("Enter password: ")

if len(password) >= 8:
    print("Password accepted")
else:
    print("Password too short")
    print("Must be at least 8 characters")

balance = 50
purchase_amount = 75

if balance >= purchase_amount:
    print("Purchase approved")
    balance -= purchase_amount
else:
    print("Insufficient funds")
    print(f"You need ${purchase_amount - balance} more")

If-Elif-Else Chain

Handling multiple conditions with elif (else if) statements.

score = 87

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"  # This will execute
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade: {grade}")

# Traffic light example
light = "yellow"

if light == "green":
    print("Go")
elif light == "yellow":
    print("Slow down")  # This will execute
elif light == "red":
    print("Stop")
else:
    print("Invalid light color")

Nested If Statements

Using if statements inside other if statements for complex logic.

age = 25
has_license = True
has_insurance = True

if age >= 18:
    print("Age requirement met")
    if has_license:
        print("License verified")
        if has_insurance:
            print("All requirements met!")
            print("You can rent the car")
        else:
            print("Insurance required")
    else:
        print("License required")
else:
    print("Must be 18 or older")

Compound Conditions

Combining multiple conditions using and, or, not operators.

# AND operator - all must be True
username = "admin"
password = "secure123"

if username == "admin" and password == "secure123":
    print("Login successful")

# OR operator - at least one must be True
is_member = False
has_coupon = True

if is_member or has_coupon:
    print("Discount applied!")  # This will execute

# NOT operator - inverts the condition
is_banned = False

if not is_banned:
    print("User can post comments")  # This will execute

# Complex combination
age = 16
has_parent_consent = True

if (age >= 18) or (age >= 13 and has_parent_consent):
    print("Can create account")  # This will execute

Best practices

  • Use proper indentation (4 spaces) for code blocks inside if statements
  • Keep conditions simple and readable - break complex logic into separate variables
  • Use elif instead of multiple separate if statements for mutually exclusive conditions
  • Consider the order of conditions in elif chains - put most likely cases first
  • Avoid deeply nested if statements - consider using functions or restructuring logic
  • Use comparison chaining in Python: (if 0 < x < 10:) instead of (if x > 0 and x < 10:)

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

for
The for loop in Python is used to iterate over sequences like lists, tuples, strings, or any iterable object. Unlike traditional for loops in other languages that use counters, Python's for loop is more like a "for each" loop, automatically handling the iteration details. It's one of the most commonly used constructs in Python for processing collections and repeating actions.
while
The while loop repeats a block of code as long as its condition remains True. Unlike a for loop, which iterates a known number of times over a sequence, a while loop is ideal when you don't know in advance how many iterations you'll need - like waiting for valid user input or running until some external condition changes. A while loop can also have an optional else clause that runs if the loop finishes normally, without hitting a break.
break and continue
break and continue give you fine-grained control over loop execution. break immediately exits the nearest enclosing loop entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the next one, without exiting the loop. Both work inside for and while loops.
pass
pass is a null operation - a statement that does absolutely nothing when executed. It exists purely to satisfy Python's syntax, which requires every block (function, class, loop, conditional) to contain at least one statement. pass is commonly used as a temporary placeholder while you're still planning out code, or to intentionally leave a branch empty.