Chapter 6: Repeating Yourself - The Power of Loops

In the last chapter, you taught your program how to make decisions. Now, let's give it the power of repetition. Imagine you needed to print "Hello!" five times. You could write:

print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")

That works, but what if you needed to do it 100 times? Or 1,000 times? Copying and pasting code is tedious and makes your programs long and difficult to manage. This is where loops come in. Loops allow you to execute a block of code multiple times, saving you from repetitive work.

Python has two main types of loops: the for loop and the while loop.

The for Loop: Looping a Specific Number of Times

A for loop is used when you want to iterate over a sequence of items, running a block of code for each item. Think of it as saying, "for each thing in this collection, do this action."

The most common way to create a for loop that runs a set number of times is by using the built-in range() function.

Using range()

The range() function generates a sequence of numbers that you can loop over.

1. range(stop) If you give range() one number, it will generate a sequence from 0 up to (but not including) that number.

# This will loop 5 times, with the variable 'i' taking on the values 0, 1, 2, 3, 4
for i in range(5):
    print("Hello! This is loop number:", i)

Output:

The variable i is a temporary variable that holds the current number in the sequence for each iteration of the loop. You can name it anything you want, but i (for "index") is a common convention.

2. range(start, stop) You can also provide a starting number. The loop will start at the first number and go up to (but not including) the second number.

Output:

Looping Over a String

You can also use a for loop to iterate over the characters in a string:

Output:

The while Loop: Looping as Long as a Condition is True

What if you don't know exactly how many times you need to loop? What if you want to loop until something specific happens? For this, we use a while loop.

A while loop will repeatedly execute a block of code as long as its condition remains True.

The structure is:

Here's an example that counts from 1 to 5:

This loop has three key parts:

  1. Initialization: We create a variable (count) and set its starting value before the loop begins.

  2. Condition: The loop checks count <= 5 at the beginning of every iteration. If it's True, the code inside runs. If it's False, the loop stops.

  3. Update: Inside the loop, we must do something to change the variable in the condition. Here, count += 1 increases the count by one. If we forget this step, the condition count <= 5 will always be true, and our program will be stuck in an infinite loop!

The Danger of Infinite Loops

If you forget to update the variable in your while loop's condition, the loop will run forever.

If you accidentally run code with an infinite loop, you'll usually need to stop the program manually. In most terminals and code editors, you can do this by pressing Ctrl+C.

Loop Control Statements: break and continue

Sometimes you need to fine-tune your loop's behavior. You might want to exit the loop early or skip a specific iteration.

break: Exiting a Loop

The break statement immediately terminates the loop, regardless of the loop's condition. The program then continues with the code that comes after the loop.

Output:

Notice it never printed Current number: 3 or 4. As soon as i was 3, the break statement was executed and the loop was over.

continue: Skipping an Iteration

The continue statement ends the current iteration and jumps to the top of the loop to start the next one.

Output:

When i was 2 or 4, the if condition was true, and continue was executed. This skipped the print(i) line for that iteration and moved on to the next number in the range.

Summary and What's Next

Loops are a fundamental concept in programming that allow you to automate repetitive tasks efficiently.

  • for loops are best when you know how many times you want to loop or when you want to iterate over a sequence (like a range of numbers or a string).

  • while loops are ideal when you want to keep looping as long as a certain condition is true.

  • break lets you exit a loop entirely.

  • continue lets you skip the current iteration and move to the next.

You can now make your programs make decisions (if/elif/else) and repeat actions (for/while). The combination of these tools allows you to write much more complex and interesting programs.

In the next chapter, we'll look at one of the most useful and common data structures in Python: lists. Lists will give you a powerful way to store and organize collections of data, which you can then process with the loops you've just learned!

Practice Time!

  1. Write a for loop that prints the numbers from 10 down to 1.

  2. Create a simple "countdown" program using a while loop that starts at 10 and, in each iteration, prints the current number and then waits for one second (hint: you'll need to import time and then use time.sleep(1) inside the loop). The loop should stop after printing "1".

  3. Write a for loop that goes from 1 to 20. Inside the loop, use if and continue to print only the numbers that are divisible by 3.

Last updated