Introduction to Python Programming

Andrew J. Pounds, Ph.D.

๐Ÿ”„ Exercise Seven: Looping Structures

One of the most powerful features of programming is the ability to repeat a block of code multiple times. This is called looping (or iteration). Python provides two main types of loops: the while loop and the for loop. Each has its strengths, and knowing when to use which will make you a more effective programmer.

What You'll Learn:
  • The two types of loops in Python: while and for
  • How to use the range() function with for loops
  • When to use each type of loop
  • How to control loops with break and continue
  • How to nest loops inside each other
๐Ÿ’ก Why Do We Need Different Types of Loops?

Think of it this way: sometimes you know exactly how many times you want to repeat something (like "do this 10 times"), and sometimes you don't know in advanceโ€”you just want to keep going until something happens (like "keep asking until the user types 'quit'"). Python gives you the right tool for each situation!

๐Ÿ—บ๏ธ 1. Overview: Two Types of Loops

Loop Type Best Used When... Basic Structure
while You don't know how many iterations you need; loop continues until a condition becomes false while condition:
for You know how many iterations you need, or you're iterating over a sequence for variable in range():
๐Ÿ’ก Quick Rule of Thumb:
  • Know the number of iterations? โ†’ Use for
  • Don't know when to stop? โ†’ Use while

๐Ÿ” 2. The while Loop (Review)

You've already learned about the while loop in Exercise Five. Let's quickly review it before introducing the for loop.

while Repeats while a condition is True
while condition:
    # code to repeat
    # update the condition variable!

Example: Counting with while

# Count from 1 to 5 using while
count = 1

while count <= 5:
    print(count)
    count += 1

print("Done!")
1
2
3
4
5
Done!

Key Characteristics of while Loops

  • Condition checked first: The condition is checked before each iteration
  • May not run at all: If the condition is false initially, the loop body never executes
  • Manual update required: You must update the loop variable yourself to avoid infinite loops
  • Flexible: Can be used when you don't know how many iterations you'll need
โš ๏ธ Remember: Always make sure something inside the loop will eventually make the condition false, or you'll create an infinite loop!

๐Ÿ”ข 3. The for Loop

The for loop is Python's way of iterating a specific number of times. It's often simpler and cleaner than a while loop when you know in advance how many iterations you need.

for Repeats for each value in a sequence
for variable in range(n):
    # code to repeat n times

Your First for Loop

# Print "Hello" 5 times
for i in range(5):
    print("Hello")
Hello
Hello
Hello
Hello
Hello

How Does This Work?

  1. range(5) generates the sequence: 0, 1, 2, 3, 4
  2. The loop runs once for each value in the sequence
  3. Each time through, the variable i takes on the next value
  4. After the last value (4), the loop ends

Using the Loop Variable

The loop variable (commonly named i) holds the current value from the range:

# See what values i takes
for i in range(5):
    print("i =", i)
i = 0
i = 1
i = 2
i = 3
i = 4
๐Ÿ’ก Note: range(5) starts at 0 and goes up to but does not include 5. This is a common pattern in programming called "zero-indexing."

๐Ÿ“ 4. The range() Function

The range() function is your best friend when using for loops. It generates a sequence of numbers that the loop iterates through.

Three Ways to Use range()

Syntax Description Example Produces
range(stop) 0 to stop-1 range(5) 0, 1, 2, 3, 4
range(start, stop) start to stop-1 range(1, 6) 1, 2, 3, 4, 5
range(start, stop, step) start to stop-1, counting by step range(0, 10, 2) 0, 2, 4, 6, 8

Example: range(stop) - One Argument

# Count from 0 to 4
for i in range(5):
    print(i)
0
1
2
3
4

Example: range(start, stop) - Two Arguments

# Count from 1 to 5
for i in range(1, 6):
    print(i)
1
2
3
4
5

Example: range(start, stop, step) - Three Arguments

# Count by 2s from 0 to 10
for i in range(0, 11, 2):
    print(i)
0
2
4
6
8
10

Counting Backwards

Use a negative step to count down:

# Countdown from 5 to 1
for i in range(5, 0, -1):
    print(i)
print("Blastoff!")
5
4
3
2
1
Blastoff!
๐Ÿ“Œ Important: When counting backwards, the stop value is still excluded. So range(5, 0, -1) goes from 5 down to 1 (not 0).

โš–๏ธ 5. Comparing while and for

Let's see the same task done with both types of loops:

Task: Print the numbers 1 through 5

Using while:
count = 1
while count <= 5:
    print(count)
    count += 1
Using for:
for count in range(1, 6):
    print(count)

Both produce the same output:

1
2
3
4
5
โœ… Why for is Often Better for Counting:
  • Shorter and cleaner code
  • No need to initialize the counter variable before the loop
  • No need to manually increment the counter
  • No risk of forgetting to update the counter (infinite loop impossible)

When to Use Which?

Situation Best Choice Why?
Repeat exactly N times for Cleaner, automatic counting
Count through a range of numbers for Built-in range() makes it easy
Repeat until user says stop while Don't know iterations in advance
Input validation (keep asking until valid) while Don't know how many tries needed
Game loop (play until game over) while Condition-based termination
Process data until end while Unknown amount of data

๐ŸŽฎ 6. Loop Control: break and continue

Sometimes you need more control over your loops. Python provides two special keywords to help:

The break Statement

The break statement immediately exits the loop, skipping any remaining iterations.

# Find the first number divisible by 7 between 1 and 100
for num in range(1, 101):
    if num % 7 == 0:
        print("Found it:", num)
        break

print("Loop finished")
Found it: 7
Loop finished

What happened? When num reached 7, the condition was true, so the program printed the number and then break immediately exited the loopโ€”it didn't continue checking 8, 9, 10, etc.

Example: break with while

# Keep asking for password, but allow only 3 attempts
secret = "python123"
attempts = 0

while True:  # Infinite loop - we'll use break to exit
    password = input("Enter password: ")
    attempts += 1
    
    if password == secret:
        print("Access granted!")
        break
    
    if attempts >= 3:
        print("Too many attempts. Locked out!")
        break
    
    print("Wrong password. Try again.")
Enter password: hello
Wrong password. Try again.
Enter password: secret
Wrong password. Try again.
Enter password: python123
Access granted!

The continue Statement

The continue statement skips the rest of the current iteration and moves to the next one.

# Print numbers 1-10, but skip multiples of 3
for i in range(1, 11):
    if i % 3 == 0:
        continue  # Skip this iteration
    print(i)
1
2
4
5
7
8
10

What happened? When i was 3, 6, or 9, the continue statement skipped the print(i) and went straight to the next iteration.

Comparison: break vs continue

Statement What It Does Loop Continues?
break Exits the loop completely No - loop ends immediately
continue Skips to the next iteration Yes - with the next value
๐Ÿ’ก Tip: Use break when you've found what you're looking for and want to stop. Use continue when you want to skip certain items but keep processing the rest.

๐Ÿช† 7. Nested Loops

You can put one loop inside another. This is called nesting. The inner loop runs completely for each iteration of the outer loop.

Basic Nested Loop Example

# Outer loop runs 3 times
for i in range(1, 4):
    print("Outer loop: i =", i)
    
    # Inner loop runs 2 times for EACH outer iteration
    for j in range(1, 3):
        print("  Inner loop: j =", j)
    
    print()  # Blank line for clarity
Outer loop: i = 1
  Inner loop: j = 1
  Inner loop: j = 2

Outer loop: i = 2
  Inner loop: j = 1
  Inner loop: j = 2

Outer loop: i = 3
  Inner loop: j = 1
  Inner loop: j = 2
Understanding Nested Loops:

The outer loop runs 3 times (i = 1, 2, 3). For each of those 3 times, the inner loop runs completely (j = 1, 2). So the inner print statement executes 3 ร— 2 = 6 times total.

Example: Multiplication Table

# Print a multiplication table (1-5)
print("Multiplication Table")
print("=" * 30)

for i in range(1, 6):
    for j in range(1, 6):
        product = i * j
        print(str(i) + " x " + str(j) + " = " + str(product))
    print()  # Blank line after each row
Multiplication Table
==============================
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

...

Example: Pattern Printing

# Print a right triangle of stars
rows = 5

for i in range(1, rows + 1):
    for j in range(i):
        print("*", end="")  # end="" prevents newline
    print()  # Move to next line after each row
*
**
***
****
*****
๐Ÿ’ก Note: The end="" parameter in print() prevents it from adding a newline after each print. This lets us print multiple characters on the same line.

๐ŸŽฏ 8. Complete Examples

Example 1: Sum Calculator with for

# Calculate the sum of numbers from 1 to N
n = int(input("Enter a positive integer: "))

total = 0
for i in range(1, n + 1):
    total += i

print("The sum of 1 to " + str(n) + " is: " + str(total))
Enter a positive integer: 10
The sum of 1 to 10 is: 55

Example 2: Find Factors

# Find all factors of a number
number = int(input("Enter a positive integer: "))

print("Factors of " + str(number) + ":")

for i in range(1, number + 1):
    if number % i == 0:
        print(i)
Enter a positive integer: 12
Factors of 12:
1
2
3
4
6
12

Example 3: Prime Number Checker

# Check if a number is prime
number = int(input("Enter a positive integer: "))

if number < 2:
    print(str(number) + " is not prime")
else:
    is_prime = True
    
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
            break
    
    if is_prime:
        print(str(number) + " is prime")
    else:
        print(str(number) + " is not prime")
Enter a positive integer: 17
17 is prime

Example 4: Guessing Game with Limited Tries

# Number guessing game with for loop (limited attempts)
import random

secret = random.randint(1, 20)
max_guesses = 5
won = False

print("I'm thinking of a number between 1 and 20.")
print("You have " + str(max_guesses) + " guesses.")
print()

for attempt in range(1, max_guesses + 1):
    guess = int(input("Guess " + str(attempt) + ": "))
    
    if guess == secret:
        print("Correct! You won in " + str(attempt) + " guesses!")
        won = True
        break
    elif guess < secret:
        print("Too low!")
    else:
        print("Too high!")

if not won:
    print("Sorry! The number was " + str(secret))
I'm thinking of a number between 1 and 20.
You have 5 guesses.

Guess 1: 10
Too low!
Guess 2: 15
Too high!
Guess 3: 12
Correct! You won in 3 guesses!

Example 5: Using Nested Loops with Functions

def print_rectangle(width, height, character):
    """Print a rectangle of the given dimensions"""
    for row in range(height):
        for col in range(width):
            print(character, end="")
        print()  # New line after each row

# Main program
print("Rectangle 1:")
print_rectangle(5, 3, "*")
print()
print("Rectangle 2:")
print_rectangle(8, 2, "#")
Rectangle 1:
*****
*****
*****

Rectangle 2:
########
########

โš ๏ธ Common Mistakes (And How to Fix Them)

Mistake 1: Off-by-One with range()

โŒ Wrong (prints 1-4, not 1-5):
for i in range(1, 5):  # Stops at 4!
    print(i)
โœ… Correct (prints 1-5):
for i in range(1, 6):  # Goes up to 5
    print(i)

Mistake 2: Modifying Loop Variable in for Loop

โŒ Wrong (doesn't work as expected):
for i in range(5):
    print(i)
    i += 10  # This has no effect on the next iteration!
โœ… Use while if you need to modify the counter:
i = 0
while i < 50:
    print(i)
    i += 10

Mistake 3: Forgetting range() in for Loop

โŒ Wrong:
for i in 5:  # ERROR! Can't iterate over an integer
    print(i)
โœ… Correct:
for i in range(5):  # Use range() to generate sequence
    print(i)

Mistake 4: Using break Outside a Loop

โŒ Wrong:
x = 5
if x > 3:
    break  # ERROR! break only works inside loops
โœ… Correct:
for i in range(10):
    if i > 3:
        break  # Works - inside a loop

Mistake 5: Wrong Indentation in Nested Loops

โŒ Wrong:
for i in range(3):
    for j in range(3):
    print(i, j)  # Wrong! Should be indented more
โœ… Correct:
for i in range(3):
    for j in range(3):
        print(i, j)  # Properly indented inside inner loop

โœ๏ธ Practice Exercises

Try writing these programs on your own!

Exercise 1: Sum of Even Numbers

Write a program using a for loop that calculates the sum of all even numbers from 2 to 100.

Hint: Use range(2, 101, 2) to generate even numbers.

Exercise 2: Factorial Calculator

Write a program that:

  1. Asks the user for a non-negative integer N
  2. Calculates N! (N factorial) using a for loop
  3. Displays the result

Remember: 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120, and 0! = 1

Exercise 3: FizzBuzz

Write a program that prints the numbers 1 to 50, but:

  • For multiples of 3, print "Fizz" instead of the number
  • For multiples of 5, print "Buzz" instead of the number
  • For multiples of both 3 and 5, print "FizzBuzz"

Exercise 4: Number Pyramid

Write a program that prints a number pyramid like this:

1
12
123
1234
12345

Hint: Use nested for loops.

Exercise 5: Prime Numbers in Range

Write a program that:

  1. Asks the user for two numbers (start and end)
  2. Prints all prime numbers between start and end

Hint: Create a function is_prime(n) and call it in your loop.

Exercise 6: Menu-Driven Calculator

Write a program with a menu that lets the user:

  1. Add two numbers
  2. Subtract two numbers
  3. Multiply two numbers
  4. Divide two numbers
  5. Exit the program

Use a while loop to keep showing the menu until the user chooses to exit.

๐Ÿ“‹ Quick Reference

Loop Structures

while loop:
while condition:
    # code to repeat
    # update condition!
for loop:
for var in range(n):
    # code runs n times

range() Function

One argument:
range(5)
# 0, 1, 2, 3, 4
Two arguments:
range(1, 6)
# 1, 2, 3, 4, 5
Three arguments:
range(0, 10, 2)
# 0, 2, 4, 6, 8
Count backwards:
range(5, 0, -1)
# 5, 4, 3, 2, 1

Loop Control

break:
break  # Exit loop now
continue:
continue  # Skip to next

โญ Key Takeaways

  • โœ“ while loops repeat while a condition is trueโ€”use when you don't know how many iterations
  • โœ“ for loops repeat for a specific number of timesโ€”use when you know the count
  • โœ“ range(n) generates numbers from 0 to n-1
  • โœ“ range(start, stop) generates numbers from start to stop-1
  • โœ“ range(start, stop, step) lets you count by any increment (including negative)
  • โœ“ break exits a loop immediately
  • โœ“ continue skips to the next iteration
  • โœ“ Nested loops: the inner loop runs completely for each iteration of the outer loop
  • โœ“ Always indent code inside loops (and indent again for nested structures)

โ“ Need Help?

If your program doesn't work, check these common issues:

  1. TypeError: 'int' object is not iterableโ€”Did you forget range() in your for loop?
  2. Off-by-one errorsโ€”Remember that range() excludes the stop value
  3. Infinite while loopโ€”Are you updating the condition variable inside the loop?
  4. 'break' outside loopโ€”break and continue only work inside loops
  5. Nested loop not workingโ€”Check your indentation carefully
๐Ÿ’ก Debugging Tip: Add print statements to see what your loop is doing:
for i in range(5):
    print("DEBUG: i =", i)  # See the loop variable
    # rest of your code
Remember: Loops are fundamental to programming! The for loop is perfect when you know how many times to repeat, while the while loop shines when you need to repeat until some condition is met. Master both, and you'll be able to tackle almost any repetitive task in programming!