CS 111 › Lesson 3 of 12

Conditionals: if / elif / else

Lesson 3 · CS 111: Programming I — Python · OKSTEM College

if / elif / else

A conditional lets your program make decisions — executing different code depending on whether a condition is True or False.

if condition: # runs when condition is True elif other_condition: # runs when first is False, this is True else: # runs when all above are False

Indentation is the block. Python uses 4-space indentation (not curly braces) to mark what belongs inside an if. Wrong indentation = bug or SyntaxError.

Comparison & Boolean Operators

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal5 != 3True
> / <greater / less7 > 3True
>= / <=greater-or-equal / less-or-equal5 >= 5True
andboth must be TrueTrue and FalseFalse
orat least one TrueTrue or FalseTrue
notinverts Booleannot TrueFalse

Common mistake: = assigns a value. == compares. Writing if x = 5: is a SyntaxError in Python (C programmers watch out).

Worked Examples

Example 1 - Grade classifier

Read a score from the user and convert to int:
score = int(input("Enter score: "))
Chain elif from highest to lowest so conditions don't overlap:
if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"
Print the result: print(f"Grade: {grade}")
Why does order matter? If we checked score >= 60 first, a score of 95 would get "D" and never reach the "A" check. Always go most-restrictive first.

Example 2 - Compound conditions

# Check if a year is a leap year year = 2024 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(f"{year} is a leap year") else: print(f"{year} is not a leap year")

Output: 2024 is a leap year

2000 is divisible by 400 (leap). 1900 is divisible by 100 but not 400 (not leap). 2024 is divisible by 4 but not 100 (leap).

Practice Problems

Problem 1 - Odd or Even

Write an if/else that prints "odd" or "even" for a number n.

n = int(input("Enter a number: ")) if n % 2 == 0: print("even") else: print("odd")
The modulo operator % gives the remainder of division. Even numbers have remainder 0 when divided by 2.

Problem 2 - FizzBuzz (classic interview question)

For a number n: print "FizzBuzz" if divisible by both 3 and 5, "Fizz" if only by 3, "Buzz" if only by 5, otherwise print the number.

n = int(input("n: ")) if n % 15 == 0: # check 15 FIRST (both 3 and 5) print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n)
Key insight: check the most specific condition (divisible by 15) first, otherwise 15 would match "Fizz" and stop there.

Problem 3 - BMI Category

BMI is weight(kg) / height(m)^2. Print: "Underweight" (<18.5), "Normal" (18.5-24.9), "Overweight" (25-29.9), "Obese" (>=30).

weight = float(input("Weight (kg): ")) height = float(input("Height (m): ")) bmi = weight / height ** 2 print(f"BMI: {bmi:.1f}") if bmi < 18.5: print("Underweight") elif bmi < 25: print("Normal") elif bmi < 30: print("Overweight") else: print("Obese")

Knowledge Check

What does elif mean?

elif is conditional, not unconditional.
Correct.
That describes or, not elif.
That is what break does inside loops.
Quick Recap

elif = 'else if'. It only runs when the preceding if (and any earlier elifs) were False.

Quick Recap

elif only executes when every condition above it was False AND its own condition is True.

Quick Recap

break exits loops. elif is a conditional branch.

What is the output of: x = 7; print('big' if x > 5 else 'small')?

x=7 which is > 5, so the 'if' branch runs.
Correct - 7 > 5 is True.
This is valid Python ternary (conditional expression) syntax.
The expression evaluates to the string 'big', not the boolean True.
Quick Recap

The ternary form is val_if_true if condition else val_if_false. Since 7 > 5 is True, output is 'big'.

Quick Recap

Python supports one-line conditionals: a if cond else b. No error here.

Quick Recap

The condition (7>5) is True, but the expression returns the string 'big', not the boolean.

Which operator checks equality without assigning?

Single = assigns a value; it does not compare.
Correct - double equals is the comparison operator.
is checks object identity (same memory address), not value equality. Use == for values.
eq is not a Python operator. It's a dunder method name.
Quick Recap

x = 5 stores 5 in x. x == 5 asks 'is x equal to 5?' Use == for comparison.

Quick Recap

is tests if two variables point to the exact same object in memory. For value comparison use ==.

Quick Recap

Python comparison operators are: ==, !=, <, >, <=, >=. There is no standalone 'eq' operator.

What does not (True and False) evaluate to?

True and False = False, then not False = True.
Correct: True and False = False; not False = True.
None is a value, not the result of boolean logic here.
This is valid Python.
Quick Recap

Step by step: True and False = False. not False = True.

Quick Recap

Boolean expressions always return True or False. not(False) = True.

Quick Recap

Parentheses are valid here: not (True and False) first evaluates the inner expression, then applies not.

If score = 85, which branch runs in the grade classifier?

85 < 90, so the A branch (score >= 90) is skipped.
Correct - 85 >= 80 and 85 < 90, so the B branch runs.
The B check (score >= 80) is reached first and is True, so C is never tested.
Execution stops at B; D is never evaluated.
Quick Recap

The A branch requires score >= 90. 85 < 90, so Python moves to the next elif.

Quick Recap

elif chains stop at the first True condition. 85 >= 80 is True, so 'B' is assigned and the elif for C is skipped.

Quick Recap

elif is not like a switch - once one branch matches, all remaining elif/else branches are skipped.