LAB 05 - Control Statements in Python

Learn how to make your Python programs more complex by telling them when to do something, how many times to repeat, and when to stop. These are called control statements, and they allow us to build paths of action and repetitive structures into our code.

💡 Note: Just like Lab 04, each person and each group will be turning in Colab files’ link instead of a PDF.

Individually

  • Create notebook with your name and labmate names
  • Rename file to first-initial_full-last-name.ipynb

As a group

  • Create a notebook with the name of everyone in the group at the top
  • Rename the file to group_name.ipynb (group name on canvas)

Make sure you share this file with the course instructor and the TAs when you submit!

Why Control Statements?

Imagine you’re programming a music app interface:

  • If the user presses ▶️ Play → start the song.
  • Else if the user presses ⏸️ Pause → stop playback but remember the position.
  • Otherwise (Stop button) → clear the track position.

Or think about a shopping cart checkout screen:

  • Repeat asking for payment details while the card information is invalid.
  • Stop the process immediately if the user clicks Cancel Checkout (break).

Without control statements, Python would just run line‑by‑line, like reading a book without choices — no interactivity!

Control statements let us create programs that feel interactive, dynamic, and adaptive — the same way user interfaces adjust based on your actions.

The Three Types of Control Statements

  1. Conditionals (if, elif, else) → Decisions and branching
  2. Loops (for, while) → Repetition
  3. Loop Control (break, continue, pass) → Fine-grain loop control

In this lab we will explore each part step-by-step, practicing individually and then synthesizing a group consensus solution.


Part 1: Conditional Statements

What Are Conditional Statements?

Conditional statements let us ask questions in code:

  • If something is true → do this
  • Otherwise → do something else

This allows programs to take different paths of execution

Basic Knowledge

  • âś… if runs when the condition is true.
  • âś… elif (“else if”) runs only if the first condition was false, but a new condition is true.
  • âś… else runs when no previous condition matched.

⚠️ Gotcha: Python only runs the first true branch. Once it runs a condition, the rest are skipped.

Examples to Try and tinker with

# Example 1: Age check
age = 20
if age >= 18:
    print("You are an adult")
# Example 2: Weather condition
temperature = 50
if temperature > 60:
    print("It’s warm outside")
else:
    print("It’s chilly today")
# Example 3: Multiple possibilities
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C or below")

đź’ˇ Tip: Test the edges. What happens if score = 90? Are we handling equalities (>=) correctly?


🎯 TASK 1: Temperature Checker

Individually: (suggested 7-10 mins, or until everyone is completed individually)

  1. Ask the user to enter the temperature (use input()).
  2. If it is between 60 and 84 (inclusive) → print “It’s nice outside”.
  3. If it is 85 or higher → print “It’s hot”.
  4. Otherwise → print “It’s cold”.

Group Collaboration:

  • Compare your solutions, come to a consensus on the solution as a group.
  • Did anyone code the ranges differently?

Extra Practice

Try modifying your code for everyday situations:

  • If it’s raining → print “Bring an umbrella”.
  • If temperature is below 32 → “Watch out for ice”.
  • Think about how layered decisions in code mirror real-world decision-making in engineering systems.

Part 2: Loops

Now that you know how to make Python decide, let’s learn how to repeat.
Loops are some of the most powerful tools in programming because they can automate repeated tasks instead of you writing them again and again.

Think of them like:

  • Telling a machine to check its sensors every second.
  • Asking the grammar corrector to correct each paragraph of your report until all the paragraph is corrected.

Without loops, you’d be stuck re‑typing the same instruction dozens of times!

Two Main Types of Loops

1. For Loops – repeat a fixed number of times

The for loop is best when you know in advance how many times you want to repeat.

⚡ Note: Python’s for loop is item-based (but we can still use sequences of numbers to create range-based functionality).
That means we can loop directly over the contents of a list (or string, or other iterable), not just over numbers.

Example: Looping through list items

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

# Compare this with looping using range:
for i in range(len(fruits)):
    print(fruits[i])

In the second example, we used the range function to create a iterable collection of numbers for our for loop.

2. While Loops – repeat while condition is true

The while loop is better when you don’t know how many times to repeat. It keeps going as long as the condition remains True.

Example: Counting up

count = 0
while count < 10:
    print("Counting:", count)
    count = count + 1
print("We've reached the end!")

⚠️ Warning: If the condition never becomes False, you’ve created an infinite loop! Always make sure something inside changes the condition.


🎯 TASK 2: Number Practice

Individually: (suggested 7-10 mins, or until everyone is completed individually)

Write a for loop to print the numbers 1 to 10.

Write a while loop to count down from 5 to 1, then print “Blast off!” at the end.

Group Collaboration:

  • Compare your solutions, come to a consensus on the solution as a group.

Where would each loop type be more appropriate in real-world systems?

Extra Practice Ideas

Create a loop that prints even numbers between 1 and 20.

Modify the countdown loop to ask for user input every cycle (like a system “status check”).


Part 3: Loop Control Statements

Sometimes, you need more control inside your loops.
Maybe you want to stop early, skip a step, or just put a placeholder for code you’ll add later.
Python gives us three main tools for this: break, continue, and pass.

1. break – Stop the loop entirely

Imagine you’re searching for a specific item: once you find it, there’s no need to keep looping.

# Example: Search menu until found
number_list = [2, 1, 4, 3, 5]

for number in number_list:
    print("Checking:", number)
    if number == 3:
        print("Found the number 3!")
        break

👉 After iterating to the correct number in the list, the loop stops immediately.

2. continue – Skip this step and move on

Sometimes we don’t want to stop the loop, but just ignore certain cases.

# Example: Skip numbers divisible by 3
for i in range(1, 10):
    if i % 3 == 0:
        continue
    print(i)

👉 The loop continues, but numbers 3, 6, and 9 are skipped.

3. pass – Do nothing (placeholder)

This is useful when you want to reserve structure, but don’t know what to put inside yet.

for i in range(5):
    if i == 2:
        pass  # Placeholder - code will be added later
    else:
        print("Number:", i)


Individually: (suggested 10-15 mins, or until everyone is completed individually)

  1. Create a list with at least 5 food items.
  2. Ask the user to enter a food item they want.
  3. Write a loop that goes through the menu.
    • If the food is found, print “We have it!” and stop searching using break.
    • If the food is not in the list, print “Not available.” after the loop ends.
    • What happens if you forget to use break? Try it both ways to see the difference.

Group Collaboration:

  • Compare your solutions, come to a consensus on the solution as a group.

Extra Practice Ideas

  • Use continue to skip certain items (e.g., ignore “water” in the menu).
  • Use pass as a placeholder when you’re not ready to code all cases yet.

Part 4: Putting It Together – Guessing Game

So far you’ve learned:

  • Conditionals: Making decisions (if, elif, else)
  • Loops: Repeating instructions (for, while)
  • Loop Control: Fine-tuning repetition with break, continue, pass

Now we will bring all of this together in a small but fun project: a Guessing Game.

Example (flow): Number Guessing

Here’s a sample flow:

# Create your secret number and variable to keep track of attempts
# Take user input
# (keep track of number of attempts)
# If correct, tell them and stop taking user input
# If incorrect, tell them and continue to take user input
# If they didn't guess the correct answer, tell them what the answer was


🎯 TASK 4: Guess the Number

Individually: (suggested 10-15 mins, or until everyone is completed individually)

  1. Write a program where the computer picks a secret number between 1 and 10.
    • Hint: use import random and then random.randint(1, 10) to generate a number.
  2. Let the user guess up to 3 times.
  3. If they guess correctly → print “Correct! You win!” and end the loop.
  4. If they don’t guess correctly by the end → print “Sorry, the number was X”.

Group Collaboration:

  • Compare your solutions, come to a consensus on the solution as a group.

Extra Practice Ideas

  • Add hints: if the guess is too high, print “Too high! Try lower.”
  • Change the number of attempts (like 5 tries instead of 3).
  • Create a “play again” loop by asking the user after the game ends.

Part 5: Restaurant Ordering System

Now it’s time to combine dictionaries, loops, and conditionals into a practical mini-project.
Think of this like programming the simple core of a restaurant’s ordering kiosk 💡.

Below we give you steps that you might take to create the program

Steps

# Create a menu using a dictionary (with the keys being the menu item and the values being the cost of that item)
# Ask the user what they'd like to order (and take their input order)
# If their choice is on the menu, add that to their total cost and display the cost of the item selected and ask them what they'd like to order again
# If their choice is not on the menu, tell them and ask them what they'd like to order again
# After they've ordered so many items, give them a total
# Add tax to our total
# Get their money (input)
# If they've given you enough money, tell them their change
# If they did not give you enough, tell them that was not enough for the total amount remaining, add the amount entered to a running total, and ask for their money again

Now we’ve just algorithmically simulated a mini cash register system with these steps!


🎯 TASK 5: Restaurant Ordering Program

  • You are tasked with creating a restaurant ordering system that asks the user to order up to 3 items and tracks the total cost of the order.
  • Here, they will enter one item at a time (up to 3 times). (Not all items at once)
  • After calculating a total (to include a 6% tax), you should ask for payment (and take that payment via input.)
  • If the user doesn’t give you enough, you should keep track of how much they’ve given you and continue to ask them for payment until they give you enough money.
  • You should also display amount of change is due when they’ve given you enough money

Below are more specific things to do. You should follow the steps above to start (and add the detail code)

Individually: (suggested 15-20 mins, or until everyone is completed individually)

  1. Create a menu dictionary with at least 4 items.
  2. Ask the user to order items (let them order up to 3 times).
  3. Track the total using the dictionary values.
  4. At the end, add a 6% tax, display the final bill, and ask for payment.
  5. If payment is enough: show change. If not: tell them the payment is insufficient, and tell them the amount remaining to be paid (apply what they enter towards their bill)

Group Collaboration:

  • Compare your solutions, come to a consensus on the solution as a group.

Extra Practice Ideas

  • Let the user keep ordering until they type “done”, instead of limiting them to 3 items.
  • Print a receipt listing all the items they ordered, along with subtotal, tax, and total.
  • Add discounts (e.g., “10% off if total > $20”).
  • Expand the dictionary with categories (like “entree”, “side”, “drink”) — this mimics how real ordering systems structure menus.

Part 6: Reflection

We’ve now worked through the essential components of control statements in Python:

  • Making decisions with if / elif / else
  • Repeating tasks with for loops and while loops
  • Controlling loops with break, continue, and pass
  • Combining concepts into systems (Guessing Game, Ordering System)

These are foundational skills. As your programs get larger, you will find yourself using at least one of these concepts almost every single time you code.

🎯 Reflection Questions

Individually: (suggested 7-10 mins, or until everyone is completed individually)

Answer these briefly inside your notebook (Markdown cell at the end):

  1. In your own words, explain the difference between a for loop and a while loop.
  2. When would you use break vs. continue? Give an example for each.
  3. Which part of the restaurant ordering system was most challenging?
  4. How do you feel about the difficulty level of completing these tasks?

Group Collaboration: While no group reflection is needed here, we would suggest conferring with one another where needed to see if you come up with similar answers (and why/why not)

Deliverables

1. Individual file’s Colab link - Each person creates their own notebook

  • Your (.ipynb) that contains:
    • Tasks 1–5 (Conditionals, Loops, Loop Controls, Guessing Game, Ordering System).
    • Your Reflection questions (as a text/Markdown cell).
    • Any additional extra practice you attempted (optional, but may help learning).

2. Group file’s Colab link - One shared notebook for the group

  • Group’s (.ipynb) that contains:
    • Consensus on Tasks 1–5 (Conditionals, Loops, Loop Controls, Guessing Game, Ordering System).

đź“‹ File Organization:

  • Each task should be in its own section
  • Use text cells to separate and label each task
  • Include clear headings and explanations
  • Make sure all code runs without errors

🎯 Grading Focus:

  • Completeness: All tasks attempted and working
  • Organization: Clear structure with proper labeling
  • Functionality: Code executes correctly
  • Collaboration: Evidence of group discussion in consensus solutions

Important:

  • Your notebook must run from top to bottom without errors.
  • Use comments to explain the logic where appropriate.
  • Code should be neat and readable.

📊 How is my lab graded?

Note: Extra Practice Ideas will not be included in the grading.

Graded ItemPoints
Individual File – Task12 pts
Individual File – Task22 pts
Individual File – Task32 pts
Individual File – Task42 pts
Individual File – Task52 pts
Individual File – Final Reflection2 pts
Individual File – File Organization2 pts
Group File – Task14 pts
Group File – Task24 pts
Group File – Task34 pts
Group File – Task44 pts
Group File – Task54 pts
Group File – Organization & Collaboration (turning in one same group file)2 pts

Total Points Possible: 36 pts

Drafted by Winnie Fang and modified by Chris Dancy