> Source URL: /demos/lab-demo/cs1-loops.lab
---
title: CS1 Loops Lab
outcomes:
  - Understand the difference between for loops and while loops
  - Use loops to repeat actions a specific number of times
  - Apply the accumulator pattern to compute results
  - Use loops to process strings and validate input
---

# Loops in Python

In this lab you'll practice writing loops — one of the most fundamental tools in programming. Loops let you repeat actions without writing the same code over and over.

---

## Background

Python has two main types of loops:

**`for` loops** iterate over a sequence (like a range of numbers or characters in a string):

```python
for i in range(5):
    print(i)
```

**`while` loops** repeat as long as a condition is true:

```python
count = 0
while count < 5:
    print(count)
    count += 1
```

---

## Exercise 1: Counting Up

Write a program that prints the numbers from 1 to 10, each on its own line.

**Expected output:**

```
1
2
3
...
10
```

**Solution:**

```python
for i in range(1, 11):
    print(i)
```

---

## Exercise 2: Sum of Numbers

Write a program that computes the sum of the numbers from 1 to 100 and prints the result.

**Hint:** Create a variable to hold the running total before the loop starts.

**Expected output:**

```
The sum is 5050
```

**Solution:**

```python
total = 0
for i in range(1, 101):
    total += i
print(f"The sum is {total}")
```

---

## Exercise 3: Multiplication Table

Write a program that prints the multiplication table for a given number. Ask the user for a number, then print its multiples from 1 to 10.

**Example output (if user enters 7):**

```
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70
```

**Solution:**

```python
num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")
```

---

## Exercise 4: Input Validation

Write a program that keeps asking the user to enter a password until they type `"secret123"`. When they get it right, print a welcome message. If they get it wrong, tell them to try again.

**Example interaction:**

```
Enter password: hello
Incorrect, try again.
Enter password: secret123
Welcome!
```

**Solution:**

```python
password = input("Enter password: ")
while password != "secret123":
    print("Incorrect, try again.")
    password = input("Enter password: ")
print("Welcome!")
```

---

## Exercise 5: Counting Characters

Write a program that asks the user for a word and a letter, then counts how many times that letter appears in the word.

**Example output:**

```
Enter a word: banana
Enter a letter: a
The letter 'a' appears 3 times in 'banana'
```

**Solution:**

```python
word = input("Enter a word: ")
letter = input("Enter a letter: ")
count = 0
for char in word:
    if char == letter:
        count += 1
print(f"The letter '{letter}' appears {count} times in '{word}'")
```

---

## Exercise 6: Number Guessing Game

Write a simple number guessing game. The secret number is 42. The program should:

1. Ask the user to guess a number
2. Tell them if their guess is too high or too low
3. Keep looping until they guess correctly
4. Count and display the number of attempts

**Example interaction:**

```
Guess a number: 25
Too low!
Guess a number: 50
Too high!
Guess a number: 42
Correct! You got it in 3 attempts.
```

**Solution:**

```python
secret = 42
attempts = 0

guess = int(input("Guess a number: "))
attempts += 1

while guess != secret:
    if guess < secret:
        print("Too low!")
    else:
        print("Too high!")
    guess = int(input("Guess a number: "))
    attempts += 1

print(f"Correct! You got it in {attempts} attempts.")
```

---

## Wrap-Up

You practiced:

- **`for` loops** with `range()` for counting and accumulating
- **`for` loops** over strings for character processing
- **`while` loops** for input validation and game logic
- The **accumulator pattern** (building up a result across iterations)

These patterns show up everywhere in programming. Next, try combining loops with lists and functions to solve bigger problems.


---

## Backlinks

The following sources link to this document:

- [Lab Demo](/CCSCNE/talk.slides.llm.md)
