= 20
temperature
# Your code here
# Use an if-else statement to print weather advice
Quick Reference
Hereβs a quick reference for the basic control flow structures weβll be using:
# If statement
if condition:
# code to run if condition is True
# For loop
for item in sequence:
# code to run for each item
# While loop
while condition:
# code to run while condition is True
Hereβs our course cheatsheet on control flows:
Feel free to refer to this cheatsheet throughout the exercise if you need a quick reminder about syntax or functionality.
Exercise Overview
In this Coding Colab, youβll practice using basic control flow structures in Python. Work through these simple tasks with your partner, discussing your approach as you go.
Part 1: If Statements (20 minutes)
Task 1: Simple Weather Advice
Write a program that gives weather advice based on temperature:
- Set a variable
temperature = 20
- Use an if-else statement to print advice:
- If temperature is above 25, print βItβs a hot day, stay hydrated!β
- Otherwise, print βEnjoy the pleasant weather!β
Task 2: Grade Classifier
Create a program that assigns a letter grade based on a numerical score:
- Set a variable
score = 85
- Use if-elif-else statements to print the letter grade:
- 90 or above: βAβ
- 80-89: βBβ
- 70-79: βCβ
- 60-69: βDβ
- Below 60: βFβ
= 85
score
# Your code here
# Use if-elif-else statements to print the letter grade
Part 2: For Loops (20 minutes)
Task 3: Counting Sheep
Write a program that counts from 1 to 5, printing βsheepβ after each number:
- Use a for loop with the range() function
- Print each number followed by βsheepβ
# Your code here
# Use a for loop to count sheep
Task 4: Sum of Numbers
Calculate the sum of numbers from 1 to 10:
- Create a variable
total = 0
- Use a for loop with the range() function to add each number to
total
- After the loop, print the total
= 0
total
# Your code here
# Use a for loop to calculate the sum
Part 3: While Loops (15 minutes)
Task 5: Countdown
Create a simple countdown program:
- Set a variable
countdown = 5
- Use a while loop to print the countdown from 5 to 1
- After each print, decrease the countdown by 1
- When the countdown reaches 0, print βBlast off!β
= 5
countdown
# Your code here
# Use a while loop for the countdown
Conclusion and Discussion (5 minutes)
With your partner, briefly discuss:
- Which control structure (if, for, or while) did you find easiest to use?
- Can you think of a real-life situation where you might use each of these control structures?
Remember, itβs okay if you donβt finish all tasks. The goal is to practice and understand these concepts. Good luck and enjoy coding together!