Codectionary / Developer documentation / Python

if

An if statement runs an indented block when its condition is truthy. Optional elif branches test further conditions in order, and else handles the case where none matched. Use it to choose actions based on data.

How it works

Python checks an if/elif/else chain from top to bottom and executes only the first matching branch. Order conditions from the most specific applicable case to the broader fallback. Independent if statements can all run, which is a different behaviour.

A colon starts the suite and consistent indentation groups its statements. Four spaces is the standard style. The condition can be a comparison, a Boolean or another object with a truth value; it need not literally be True.

A branch may create a name only on some paths. If later code needs that name, assign it on every required path or give it a suitable initial value before the conditional.

Common mistakes and boundaries

Do not put a broad threshold first when it would hide a narrower branch: score >= 60 would also match a score of 95.

Avoid deeply nested decisions where named conditions or early returns would clarify the rule. The credential examples use fake values to demonstrate branching, not secure authentication or password storage.

Try it yourself

Test the grade chain with 59, 60, 79, 80, 89 and 90. Explain the boundary cases. Then decide what your program should do with a score outside 0–100 instead of silently assigning it a grade.

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!")
  1. These are separate if statements, so each qualifying decision runs independently.
  2. Expected output: You are an adult It's hot outside! Remember to stay hydrated 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")
  1. In a terminal, the sample text examplepass passes the length-only demonstration. The balance branch fails separately. Do not use this length check as an authentication policy.
  2. Expected output with the sample input below: Enter password: Password accepted Insufficient funds You need $25 more
  3. Run in a local terminal or an editor with console input. Sample input, one response per line: examplepass

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")
  1. The grade chain stops at the first satisfied threshold. The light chain chooses one matching label.
  2. Expected output: Your grade: B Slow down

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")
  1. Each inner check is reached only after all enclosing checks succeed; this illustrates nesting rather than a recommended shape for every validation function.
  2. Expected output: Age requirement met License verified All requirements met! You can rent the car

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
  1. The conditions demonstrate and, or and not with fake values. None of these examples implements authentication or an account-eligibility policy.
  2. Expected output: Login successful Discount applied! User can post comments Can create account

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
  • Order elif branches so broader conditions do not hide more specific cases.
  • 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:)

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading