How to make decisions with if/else

Write a conditional

Python executes an if block only when its condition is truthy. A colon starts the block, and consistent indentation defines it.

temperature = 28
if temperature > 25:
    print("It is warm")

Add alternatives

elif checks another condition only if earlier branches failed. else handles everything remaining.

score = 82
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C or below"
print(grade)

Combine and chain comparisons

Use boolean operators for compound rules. Python also supports readable chained numeric comparisons.

age = 16
has_permission = True
if 13 <= age < 18 and has_permission:
    print("Teen account allowed")

Use conditional expressions sparingly

A conditional expression selects one of two values. It is concise for simple assignments but ordinary branches are clearer for multiple actions.

balance = 25
status = "positive" if balance >= 0 else "overdrawn"
print(status)