Neural Sync Active
Conditionals โ if/elif/else
Registry Synced
Conditionals โ if/elif/else
2023 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:
- Write
ifstatements to execute code conditionally - Use
if-elsefor two-way decisions - Chain multiple conditions with
elif - Nest conditionals inside each other
- Use boolean expressions effectively
- Understand truthiness โ which values are "falsy"
๐ Prerequisites
- Operators & Expressions โ Understanding comparison and logical operators.
- Variables & Data Types โ Basic variable usage.
๐ 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:
pseudoYou are eligible to vote. Please register. This always runs.
How it works:
- Python evaluates
age >= 18โTrue. - Since the condition is
True, the indented block underifexecutes. - 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 Rendering 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:
pseudoIt's hot outside! Stay hydrated. Stay safe!
Flow:
Diagram
Rendering 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:
pseudoScore: 85, Grade: B
Key rules:
- Python checks conditions top to bottom.
- The first
Truecondition's block executes. - The rest are skipped โ even if later conditions are also True.
elseat 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:
pseudoNone 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:
pseudoEnter 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:
pseudoEnter 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:
pseudoUsername: 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:
pseudoWeight (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:
pseudoEither 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
| Concept | Syntax | Description | Example |
|---|---|---|---|
| If | if cond: | Execute block if True | if x > 0: |
| Else | else: | Execute block if all above False | else: |
| Elif | elif cond: | Check another condition | elif x == 0: |
| Nested if | if...if... | If inside another if | See example 4 |
| Ternary | x if cond else y | Inline conditional | "even" if n%2==0 else "odd" |
| Truthy | Any non-zero, non-empty value | Treated as True | 42, "hello", [1] |
| Falsy | Zero, empty, None, False | Treated as False | 0, "", 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:
pythonif 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:
pythonif 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:
pythonscore = 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:
pythonif 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?pythonx = 10 if x > 5: print("Big") elif x > 8: print("Huge") else: print("Small")Answer:pseudoBigx > 5is True (10 > 5), so the first block runs. Theelifis never checked. Q2: Fix the error:pythonif score = 100: print("Perfect!")Answer: Error:SyntaxError: invalid syntaxFix: Use==for comparison:if score == 100:Q3: What's the output of this code?pythonvalue = 0 if value: print("Truthy") else: print("Falsy")Answer:pseudoFalsy0is a falsy value in Python. So theelsebranch 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?pythonn = 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:pseudoFizzBuzz15 is divisible by both 3 and 5, so the first condition (and) is True. Q6: Why won't "A" ever print?pythonscore = 95 if score > 60: print("C") elif score > 75: print("B") elif score > 90: print("A")Answer: Becausescore > 60is True (95 > 60), the first block runs and prints "C". Theelifconditions are never evaluated. Fix by ordering from HIGHEST to LOWEST:pythonif 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 doesbool("False")return โ True or False?Answer:TrueThe 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) # adultQ10: What does this output?pythona, 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:pseudo10
a > bโ5 > 10โ False, so first condition failsb > aโ10 > 5โ True ANDb > cโ10 > 3โ True, so printsb(10)
๐ Cross-References
- Next Topic: Nested Conditionals & Logical Operators
- Previous Topic: Strings โ Basics & Operations
- BSCS1001 Computational Thinking: Conditional logic maps directly to decision diamonds in flowcharts.
- BSCS2002 PDSA: Conditionals are used in all search and sort algorithms.
- Reference: Python for Everybody, Chapter 3 โ "Conditional execution"
- Video: L21: Introduction to the if statement, L22: Tutorial on if, else and elif Join Discord Previous5. Strings BasicsNext7. Nested Conditionals