> Source URL: /demos/cs1-path/labs/lab-03.spec
---
lab_number: 3
title: Repeat After Me
outcomes: [3, 6]
difficulty: beginner
prerequisites: [lab-01, lab-02]
estimated_time: 75-90 minutes
---

# 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:

- [ ] Use `for` loops to repeat code a specific number of times
- [ ] Use `range()` to generate sequences of numbers
- [ ] Iterate through strings and lists
- [ ] Use `while` loops for condition-based repetition
- [ ] Accumulate values (sum, count) using loops

## Prerequisites

Before starting this lab, you should be comfortable with:

- [Lab 1: Hello Python](lab-01.spec.md) - variables, input/output
- [Lab 2: Making Decisions](lab-02.spec.md) - conditionals, boolean expressions

## Instructions

### Part 1: The For Loop

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

1. Print numbers 0 through 4:

```python
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!

2. You can specify start and end:

```python
# range(start, stop) - stop is NOT included
for i in range(1, 6):
    print(i)
```

**Expected output:**

```
1
2
3
4
5
```

3. Print a message multiple times:

```python
for i in range(3):
    print("Python is fun!")
```

### Part 2: Looping Through Strings

You can loop through each character in a string:

```python
word = "Hello"

for letter in word:
    print(letter)
```

**Expected output:**

```
H
e
l
l
o
```

Try this—count the vowels in a word:

```python
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:**

```python
# 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)
```

2. **Counting with a condition:**

```python
# 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")
```

3. **Building a string:**

```python
# 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:

```python
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.

2. Keep asking until valid input:

```python
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:

```python
# 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:

```python
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:

```python
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:

- [ ] Program runs without errors
- [ ] Right-side-up triangle works correctly
- [ ] Upside-down triangle works correctly
- [ ] Code handles the edge case of height = 1
- [ ] No infinite loops!

## 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


---

## Backlinks

The following sources link to this document:

- [Lab 3: Repeat After Me](/demos/cs1-path/index.path.llm.md)
- [Lab 3: Repeat After Me](/demos/cs1-path/course.outcomes.llm.md)
- [Lab 3: Repeat After Me](/demos/cs1-path/course.schedule.llm.md)
