Registry Synced

Conditionals โ€” if/elif/else

2019 words
10 min read

Reading compass

Now ยท ๐ŸŽฏ Learning Objectives

Conditionals โ€” if/elif/else

Why read this? Programs rarely follow a straight line. They need to make choices: "If the user is logged in, show their profile. Otherwise, show the login page." Conditionals are how programs make decisions based on data.

๐ŸŽฏ Learning Objectives

By the end of this topic, you will be able to:
  1. Write if statements to execute code conditionally
  2. Use if-else for two-way decisions
  3. Chain multiple conditions with elif
  4. Nest conditionals inside each other
  5. Use boolean expressions effectively
  6. Understand truthiness โ€” which values are "falsy"

๐Ÿ“‹ Prerequisites


๐Ÿ“– Core Content

6.1 What Problem Do Conditionals Solve?

Intuition: In everyday life, you make decisions constantly: "If it's raining, take an umbrella. Otherwise, wear sunglasses." Conditionals let your program do the same โ€” execute different code depending on conditions.

6.2 The if Statement โ€” Simplest Decision

python
# runnable
age = 18
if age >= 18:
    print("You are eligible to vote.")
    print("Please register.")
print("This always runs.")
Output:
pseudo
You are eligible to vote.
Please register.
This always runs.
How it works:
  1. Python evaluates age >= 18 โ†’ True.
  2. Since the condition is True, the indented block under if executes.
  3. After the block, execution continues with the next unindented line. Syntax rules:
  • The condition must end with a colon :.
  • The body must be indented (usually 4 spaces).
  • All lines in the block must have the same indentation. (Diagram)

6.3 if-else โ€” Two Paths

python
# runnable
temperature = 35
if temperature > 30:
    print("It's hot outside!")
    print("Stay hydrated.")
else:
    print("It's cool outside.")
    print("Enjoy the weather!")
print("Stay safe!")
Output:
pseudo
It's hot outside!
Stay hydrated.
Stay safe!
Flow: (Diagram)

6.4 elif โ€” Multiple Conditions

When you have more than two possibilities, chain them with elif:
python
# runnable
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"Score: {score}, Grade: {grade}")
Output:
pseudo
Score: 85, Grade: B
Key rules:
  • Python checks conditions top to bottom.
  • The first True condition's block executes.
  • The rest are skipped โ€” even if later conditions are also True.
  • else at the end catches everything not caught above.

6.5 Truthiness and Falsy Values

Not just True and False โ€” Python treats many values as "truthy" or "falsy":
python
# runnable
# These are all FALSY (treated as False):
if 0:
    print("0 is truthy")
if "":
    print("Empty string is truthy")
if None:
    print("None is truthy")
if []:
    print("Empty list is truthy")
if {}:
    print("Empty dict is truthy")
print("None of the above printed because all are falsy.")
# Everything else is TRUTHY:
if 42:
    print("42 is truthy")
if "Hello":
    print("Non-empty string is truthy")
if [1, 2]:
    print("Non-empty list is truthy")
Output:
pseudo
None of the above printed because all are falsy.
42 is truthy
Non-empty string is truthy
Non-empty list is truthy
Falsy values (complete list): False, 0, 0.0, "" (empty string), None, [] (empty list), {} (empty dict), () (empty tuple), set() (empty set).

6.6 Worked Example 1: Even or Odd

python
# runnable
number = int(input("Enter a number: "))
if number % 2 == 0:
    print(f"{number} is even.")
else:
    print(f"{number} is odd.")
# Also check divisibility by 5 and 10
if number % 10 == 0:
    print(f"{number} is divisible by 10.")
elif number % 5 == 0:
    print(f"{number} is divisible by 5 but not 10.")
Output:
pseudo
Enter a number: 15
15 is odd.
15 is divisible by 5 but not 10.

6.7 Worked Example 2: Number Classifier

python
# runnable
num = float(input("Enter a number: "))
if num > 0:
    print(f"{num} is positive.")
    if num.is_integer() and num > 100:
        print("It's a large positive integer.")
elif num < 0:
    print(f"{num} is negative.")
    if num > -10:
        print("It's a small negative number (between -10 and 0).")
else:
    print("The number is zero.")
Output:
pseudo
Enter a number: -5
-5.0 is negative.
It's a small negative number (between -10 and 0).

6.8 Worked Example 3: Login System

python
# runnable
username = input("Username: ")
password = input("Password: ")
# Simulated database
correct_user = "admin"
correct_pass = "secret123"
if username == correct_user and password == correct_pass:
    print("Login successful!")
    print("Welcome, admin.")
elif username == correct_user:
    print("Incorrect password.")
elif password == correct_pass:
    print("Username not found.")
else:
    print("Both username and password are incorrect.")
Output:
pseudo
Username: admin
Password: wrong
Incorrect password.

6.9 Worked Example 4: Nested Conditionals โ€” BMI Calculator

python
# runnable
weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
bmi = weight / (height ** 2)
print(f"Your BMI: {bmi:.1f}")
if bmi < 18.5:
    print("Category: Underweight")
    print("Tip: Consider a balanced diet to gain healthy weight.")
elif bmi < 25:
    print("Category: Normal weight")
    print("Tip: Maintain your healthy lifestyle!")
elif bmi < 30:
    print("Category: Overweight")
    print("Tip: Regular exercise can help.")
else:
    print("Category: Obese")
    if bmi >= 40:
        print("(Class III - Severe obesity)")
    elif bmi >= 35:
        print("(Class II - Moderate obesity)")
    else:
        print("(Class I - Mild obesity)")
    print("Tip: Consult a healthcare professional.")
Output:
pseudo
Weight (kg): 85
Height (m): 1.75
Your BMI: 27.8
Category: Overweight
Tip: Regular exercise can help.

6.10 Worked Example 5: Short-Circuit Evaluation in Conditionals

python
# runnable
x = 0
y = 10
# Safe division using short-circuit
if x != 0 and y / x > 2:
    print("Condition met")
else:
    print("Either x is 0 or y/x <= 2")
    # Thanks to short-circuit, y/x never executed when x==0!
Output:
pseudo
Either x is 0 or y/x <= 2
If we wrote if y / x > 2 and x != 0:, Python would evaluate y / x FIRST (when x=0), causing ZeroDivisionError. Always put the cheaper/safer check first.

๐Ÿ“ Key Concepts Reference

ConceptSyntaxDescriptionExample
Ifif cond:Execute block if Trueif x > 0:
Elseelse:Execute block if all above Falseelse:
Elifelif cond:Check another conditionelif x == 0:
Nested ifif...if...If inside another ifSee example 4
Ternaryx if cond else yInline conditional"even" if n%2==0 else "odd"
TruthyAny non-zero, non-empty valueTreated as True42, "hello", [1]
FalsyZero, empty, None, FalseTreated as False0, "", None, []

โš ๏ธ Common Pitfalls

Pitfall 1: Using = Instead of ==

The mistake: if x = 5: The error: SyntaxError: invalid syntax Why: = is assignment, not comparison. Python 3 doesn't allow assignment in conditionals. Fix: Use ==: if x == 5:

Pitfall 2: Indentation Errors

The mistake:
python
if x > 0:
print("Positive")   # no indent!
The error: IndentationError: expected an indented block after 'if' statement Why: Python requires indentation to identify the block. Fix: Use 4 spaces: print("Positive")

Pitfall 3: Using elif After else

The mistake:
python
if x > 0:
    print("Positive")
else:
    print("Not positive")
elif x == 0:
    print("Zero")   # This is unreachable!
The error: SyntaxError: invalid syntax Why: elif can only come after if or another elif, not after else. else must be the last branch. Fix: Put elif x == 0: before the else.

Pitfall 4: Overlapping Conditions

The mistake:
python
score = 75
if score >= 70:
    print("B")
elif score >= 80:
    print("A")   # This NEVER runs!
Why: The first True condition runs. If score is 85, score >= 70 is True, so "B" prints and the rest is skipped. Fix: Order from highest to lowest: check >= 80 first, then >= 70.

Pitfall 5: Forgot else Catches Everything

The mistake:
python
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
# What if x == 0? No output!
Fix: Add else: print("Zero") to handle the remaining case.

๐Ÿ“ Practice Questions

Q1: What does this code output?
python
x = 10
if x > 5:
    print("Big")
elif x > 8:
    print("Huge")
else:
    print("Small")
Answer:
pseudo
Big
x > 5 is True (10 > 5), so the first block runs. The elif is never checked. Q2: Fix the error:
python
if score = 100:
    print("Perfect!")
Answer: Error: SyntaxError: invalid syntax Fix: Use == for comparison: if score == 100: Q3: What's the output of this code?
python
value = 0
if value:
    print("Truthy")
else:
    print("Falsy")
Answer:
pseudo
Falsy
0 is a falsy value in Python. So the else branch executes. Q4: Write a program that takes a number and prints "Positive", "Negative", or "Zero".
Answer:
python
# runnable
num = float(input("Enter a number: "))
if num > 0:
    print("Positive")
elif num < 0:
    print("Negative")
else:
    print("Zero")
Q5: What does this output?
python
n = 15
if n % 3 == 0 and n % 5 == 0:
    print("FizzBuzz")
elif n % 3 == 0:
    print("Fizz")
elif n % 5 == 0:
    print("Buzz")
else:
    print(n)
Answer:
pseudo
FizzBuzz
15 is divisible by both 3 and 5, so the first condition (and) is True. Q6: Why won't "A" ever print?
python
score = 95
if score > 60:
    print("C")
elif score > 75:
    print("B")
elif score > 90:
    print("A")
Answer: Because score > 60 is True (95 > 60), the first block runs and prints "C". The elif conditions are never evaluated. Fix by ordering from HIGHEST to LOWEST:
python
if score > 90: print("A")
elif score > 75: print("B")
elif score > 60: print("C")
Q7: Write a program that checks if a year is a leap year.
Answer:
python
# runnable
year = int(input("Enter year: "))
if year % 400 == 0:
    print(f"{year} is a leap year.")
elif year % 100 == 0:
    print(f"{year} is NOT a leap year.")
elif year % 4 == 0:
    print(f"{year} is a leap year.")
else:
    print(f"{year} is NOT a leap year.")
Q8: What does bool("False") return โ€” True or False?
Answer: True
The string "False" is non-empty, so it's truthy. bool("False") โ†’ True. Only the empty string "" is falsy. Q9: Write a ternary expression that returns "adult" if age >= 18, else "minor".
Answer:
python
# runnable
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult
Q10: What does this output?
python
a, b, c = 5, 10, 3
if a > b and a > c:
    print(a)
elif b > a and b > c:
    print(b)
else:
    print(c)
Answer:
pseudo
10
  • a > b โ†’ 5 > 10 โ†’ False, so first condition fails
  • b > a โ†’ 10 > 5 โ†’ True AND b > c โ†’ 10 > 3 โ†’ True, so prints b (10)

๐Ÿ”— Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.