Lab 3: Repeat After Me

Overview

Many programming tasks involve doing something multiple times—processing items in a list, counting up to a number, or repeating until a condition is met. In this lab, you'll learn to use loops to automate repetitive tasks.

Learning Objectives

By completing this lab, you will be able to:

Prerequisites

Before starting this lab, you should be comfortable with:

Instructions

Part 1: The For Loop

A for loop repeats code for each item in a sequence.

  1. Print numbers 0 through 4:
for i in range(5):
    print(i)

Expected output:

0
1
2
3
4

Notice that range(5) gives us 5 numbers, but they start at 0. This is common in programming!

  1. You can specify start and end:
# range(start, stop) - stop is NOT included
for i in range(1, 6):
    print(i)

Expected output:

1
2
3
4
5
  1. Print a message multiple times:
for i in range(3):
    print("Python is fun!")

Part 2: Looping Through Strings

You can loop through each character in a string:

word = "Hello"

for letter in word:
    print(letter)

Expected output:

H
e
l
l
o

Try this—count the vowels in a word:

word = "programming"
vowel_count = 0

for letter in word:
    if letter in "aeiou":
        vowel_count = vowel_count + 1

print("The word", word, "has", vowel_count, "vowels")

Part 3: Accumulating Values

A common pattern is using a loop to build up a result.

  1. Summing numbers:
# Add up numbers 1 through 10
total = 0

for num in range(1, 11):
    total = total + num
    print("Adding", num, "- Total so far:", total)

print("Final total:", total)
  1. Counting with a condition:
# Count even numbers from 1 to 20
even_count = 0

for num in range(1, 21):
    if num % 2 == 0:  # % gives remainder; even numbers have remainder 0
        even_count = even_count + 1

print("There are", even_count, "even numbers between 1 and 20")
  1. Building a string:
# Create a string of asterisks
stars = ""

for i in range(5):
    stars = stars + "*"
    print(stars)

Expected output:

*
**
***
****
*****

Part 4: While Loops

A while loop repeats as long as a condition is True. Use this when you don't know exactly how many times to repeat.

  1. Count down from 5:
count = 5

while count > 0:
    print(count)
    count = count - 1

print("Blast off!")

Expected output:

5
4
3
2
1
Blast off!

Note: Make sure the condition eventually becomes False, or you'll have an infinite loop. If that happens, press Ctrl+C to stop.

  1. Keep asking until valid input:
password = ""

while password != "secret123":
    password = input("Enter password: ")
    if password != "secret123":
        print("Wrong password, try again.")

print("Access granted!")

Part 5: Nested Loops

You can put a loop inside another loop:

# Multiplication table (1-5)
for i in range(1, 6):
    for j in range(1, 6):
        product = i * j
        print(i, "x", j, "=", product)
    print("---")  # Separator between groups

Here's a simpler example—making a rectangle of stars:

rows = 3
cols = 5

for row in range(rows):
    line = ""
    for col in range(cols):
        line = line + "*"
    print(line)

Expected output:

*****
*****
*****

Part 6: Putting It Together

Create a number guessing game with multiple attempts:

import random

secret = random.randint(1, 10)  # Random number 1-10
attempts = 0
max_attempts = 5
guessed = False

print("I'm thinking of a number between 1 and 10.")
print("You have", max_attempts, "attempts.")

while attempts < max_attempts and not guessed:
    guess = int(input("Your guess: "))
    attempts = attempts + 1

    if guess == secret:
        guessed = True
        print("Correct! You got it in", attempts, "attempts!")
    elif guess < secret:
        print("Too low!")
    else:
        print("Too high!")

if not guessed:
    print("Out of attempts! The number was", secret)

Submission

Create a program called loop_art.py that:

  1. Asks the user for a number between 1 and 10
  2. Prints a triangle of that height using asterisks

Example interaction:

Enter height (1-10): 5
*
**
***
****
*****

Then extend it to also print an upside-down triangle:

Enter height (1-10): 5
*****
****
***
**
*

Hint for the upside-down version: range() can count backwards with range(start, stop, step) where step is -1.

Push your loop_art.py to your GitHub repository.

Self-Check

Before submitting, verify:

Extension Challenges (Optional)

  1. Diamond Shape: Combine both triangles to make a diamond shape.

  2. FizzBuzz: Print numbers 1-100, but for multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz".

  3. Prime Checker: Write a program that checks if a number is prime (only divisible by 1 and itself).

Getting Help

  • Review Lecture 3: Loops (coming soon)
  • Check the course discussion forum
  • Attend office hours