Learn Python Programming  /  Control Flow  /  If...Else

If...Else

if...else lets your code make decisions. Python uses indentation, not curly braces, to mark which lines belong to which block — getting this right is essential.

Basic if Statement

R Code
age = 20

if age >= 18:
    print("You are an adult.")
Output
You are an adult.
⚠ Common Mistake
Python uses indentation (typically 4 spaces) to define a block - there are no curly braces. Mixing tabs and spaces, or inconsistent indentation, raises an IndentationError. Most editors handle this automatically once configured correctly.

if...else

R Code
age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
Output
You are a minor.

if...elif...else Chains

Python spells "else if" as a single word: elif.

R Code
score = 72

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"

print(grade)
Output
C

The Conditional (Ternary) Expression

A compact one-line way to assign a value based on a condition.

R Code
age = 15
status = "adult" if age >= 18 else "minor"
print(status)
Output
minor

Advanced: Nested Conditions

🚀 Advanced Example
Conditions can be nested to check multiple, related criteria.
R Code
age = 17
has_id = True

if age >= 18:
    print("Entry allowed.")
else:
    if has_id:
        print("Underage but has ID - manager review needed.")
    else:
        print("Entry denied.")
Output
Underage but has ID - manager review needed.

Key Points

  • Python uses indentation, not braces, to mark code blocks - be consistent (4 spaces is standard).
  • elif replaces the else if chain used in many other languages.
  • value_if_true if condition else value_if_false is Python's compact ternary expression.