Chapter 5: Control Flow in Python – Conditional Statements & Loops

1. Conditional Statements (if, elif, else)

If-Else Flow Diagram

Flowchart of conditional logic

Basic Syntax

if condition1:
    # code if condition1 is True
elif condition2:
    # code if condition2 is True
else:
    # code if all conditions are False

Example: Age Check

age = 18

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")

Output

Teenager

Exercise 1: Grade Calculator

Write a program that:

  1. Takes a score input (0-100)
  2. Prints the grade (A: 90+, B: 80-89, etc.)

2. Loops

While Loops

count = 1
while count <= 5:
    print(count)
    count += 1

For Loops

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit.upper())

Exercise 2: Number Guessing Game

Create a game that:

  1. Generates a random number (1-100)
  2. Keeps prompting the user until they guess it
  3. Gives "too high/too low" hints

3. Loop Control Statements

break

for num in range(10):
    if num == 5:
        break
    print(num)  # Stops at 4

continue

for num in range(5):
    if num == 2:
        continue
    print(num)  # Skips 2

Exercise 3: Prime Number Checker

Write a program that:

  1. Takes a number input
  2. Uses a loop to check if it's prime
  3. Breaks early if divisor found