Learn Python: Loops and Iteration (for and while)
Loops let you repeat actions in your program. Whether you want to print numbers in a certain range, process each character in a string, or keep asking a user for input until they type a certain answer, loops are the solution. Python provides two main loop structures: the for loop and the while loop. In Visual Studio Code (VS Code), you can write loops in a Python file and run them to see each iteration happen in your terminal. This lesson walks you through the basics of both loops, introduces the range() function, and explains how to use break and continue for extra control.
What will be covered
• for loops for iterating over sequences (strings, numeric ranges).
• range() function to generate sequences of numbers.
• while loops for repeating code until a condition changes.
• break to exit a loop immediately, continue to skip to the next iteration.
• Common patterns like counting up/down, accumulating values, and checking user input.
for Loops
A for loop iterates over each element in a sequence. If you want to run something for each character in a string, or for each number in a generated range, for is your friend. You typically see:
for character in "Hello":
print(character)
This prints each letter of “Hello” on a separate line. Because a string is a sequence of characters, the loop goes through them one by one. For numeric loops, you often use range().
The range() Function
range() produces a sequence of integers. range(5) creates the numbers 0 through 4. range(1, 6) goes from 1 to 5. You can specify a step if desired, like range(10, 0, -1) for counting down. In a for loop:
for num in range(1, 6):
print(num)
This prints 1, 2, 3, 4, 5. You could also go in reverse by providing a negative step, like range(5, 0, -1).
while Loops
A while loop repeats as long as its condition is True. This is useful for open-ended repetition, such as prompting a user until they type something specific.
counter = 3
while counter > 0:
print("Counting down:", counter)
counter = counter - 1
print("Done!")
The loop continues until counter > 0 is no longer True. Then Python moves on.
break and continue
break stops a loop immediately, even if the original sequence or condition isn’t finished. continue skips the rest of the current iteration and moves on to the next one.
for num in range(1, 6):
if num == 3:
break
print("Number:", num)
print("Loop ended early!")
Here, once num is 3, the break triggers and exits the loop, so 4 and 5 never print. If you replaced break with continue, then it would skip printing 3 but still continue with 4 and 5.
Flow of Loop Execution
The diagram below illustrates how a while loop condition is checked each iteration:
A for loop does something similar, except it automatically progresses through each element in a sequence or each integer in a range.
Practice Exercises
- Use a for loop with range() to print the first 10 natural numbers (1 through 10). Then modify it to print the numbers 10 down to 1. Confirm each sequence is correct.
- Write a loop that computes the factorial of a given number n. For example, if n=5, the result is 5 * 4 * 3 * 2 * 1 = 120. Use a for loop and a running product variable to accumulate the result.
- Create a while loop that asks the user for a secret word, then breaks out if they guess correctly. Print a friendly message if they succeed. If they guess incorrectly, print a hint (like "Try again") and repeat. Stop the loop only when the correct word is entered.
- Challenge: build a simple multiplication quiz. Use a loop to ask 5 different multiplication questions. For each, compare the user’s answer with the correct result. Keep a score of correct answers, and print the final score after the loop ends.
- Optional: experiment with break and continue in a for loop over range(1, 6). If the number is 3, continue so it skips printing 3 but keeps printing other numbers. Observe how the loop flow changes.
Summary
Loops enable repetition in your code. for loops iterate over a finite range or sequence, while while loops continue until a condition becomes False. You can stop a loop prematurely with break or skip an iteration using continue. These constructs are essential for handling lists of data, counting down, building quizzes, and more. Combined with conditional statements, loops let you build logic that processes data in flexible ways and automates repeated actions in Python.