Day 3: Control Flow – Conditionals & Loops
Today, you'll learn how to control the flow of your Python programs using conditionals and loops.
This will allow your programs to make decisions and repeat actions based on conditions. Follow
the plan below and work through the examples and exercises.
Step 1: Conditionals
What Are Conditionals?
• Definition: Conditionals allow you to execute certain blocks of code only if specific
conditions are met.
• Keywords:
o if: Checks a condition and executes the block if the condition is true.
o elif: Short for “else if,” checks another condition if the previous if (or elif) was false.
o else: Executes a block of code if none of the preceding conditions are true.
Syntax & Example:
# Example: Weather message based on temperature
temperature = 22
if temperature > 30:
print("It's hot outside!")
elif temperature < 15:
print("It's cold outside!")
else:
print("The weather is moderate.")
Key Points:
• Indentation: Python uses indentation (commonly 4 spaces) to define the code blocks.
• Comparison Operators: Use operators like >, <, ==, !=, >=, and <= to compare values.
Exercise:
• Task: Write a script that:
1. Assigns a numeric value to a variable score.
2. Prints:
▪ “Excellent” if score is 90 or above,
▪ “Good” if score is between 70 and 89,
▪ “Needs Improvement” if score is below 70.
• Hint: Use if, elif, and else statements.
Step 2: Loops
Loops allow you to execute a block of code multiple times.
A. For Loops
Purpose:
• Iterate over items in a sequence (like lists, strings, or ranges).
Syntax & Example:
# Iterating over a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range() to iterate a set number of times
for i in range(5): # 0 to 4
print("Number:", i)
B. While Loops
Purpose:
• Execute a block of code repeatedly as long as a condition is true.
Syntax & Example:
# Example: Print numbers from 0 to 4 using a while loop
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increment count to avoid an infinite loop
Exercise:
• Task: Write a script that:
1. Uses a for loop to print each character in a string (e.g., "Python").
2. Uses a while loop to print the numbers 1 to 5.
• Challenge: Combine conditionals and loops. For example, use a loop to iterate through
numbers 1 to 10 and print whether each number is even or odd.
Step 3: Experiment in the Interactive Shell
1. Open the Python Interactive Shell:
In your terminal, type:
python
2. Try Out Some Commands:
# Test conditionals
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# Test for loop with range
for num in range(3):
print("Iteration", num)
# Test while loop
n=3
while n > 0:
print("n is", n)
n -= 1
3. Exit the Shell:
Type:
exit()