CS 101 – Introduction to Computer Science
Lecture 4: Control Flow – if, else, and elif
Date: October 2, 2024
Lecture Objectives:
• Understand conditional logic in Python
• Learn to use if, else, and elif statements
• Discuss Boolean expressions and truth tables
Key Concept: Control Flow
Control flow = directing the execution path of a program based on conditions
Basic if Statement:
x=5
if x > 0:
print("x is positive")
• The code inside the if block runs only if the condition is True
• Indentation is required (4 spaces is standard in Python)
else and elif:
x = -3
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
• elif = “else if” → checks another condition
• else = catch-all if none of the above are True
Boolean Expressions:
• Python uses True and False (capitalized)
• Comparison operators:
• == (equal)
• != (not equal)
• > / < (greater/less than)
• >= / <=
age = 18
if age >= 18:
print("You can vote!")
Common Mistakes:
• Using = instead of == in conditions
• Forgetting the colon : at the end of if, elif, or else
• Misaligned indentation = IndentationError
Nested Conditions:
score = 92
if score >= 90:
if score > 95:
print("A+")
else:
print("A")
Nested if blocks allow more specific conditions inside broader ones.
Homework:
• Programming Exercise 2: Build a grade calculator
• Reading: Textbook Chapter 3 – Conditionals
• Optional: Practice problems on CodingBat