Python Programming Loops Explained
Introduction to Loops
Repeating Yourself, the Smart Way
In everyday life, we perform repetitive tasks all the time. Think about dealing a deck of cards, washing a stack of dishes, or sending out party invitations. You do the same basic actions over and over again.
Programming is no different. Often, you'll need your program to perform the same task multiple times. You could copy and paste your code, but that's inefficient and prone to errors. A much smarter way is to use a loop.
loop
noun
A control flow structure that allows a block of code to be executed repeatedly.
Loops are a fundamental concept in programming. They let you automate repetitive jobs, making your code shorter, cleaner, and easier to manage. Python has two main types of loops: for loops and while loops.
Loops help you repeat actions without writing the same code over and over.
The For Loop
A for loop is perfect for when you know exactly how many times you want to repeat an action. It iterates over a sequence of items, executing a block of code once for each item.
A common way to create a sequence of numbers is with the range() function. For example, range(5) generates a sequence of numbers from 0 up to, but not including, 5. That's 0, 1, 2, 3, 4.
# This loop runs 5 times, for numbers 0 through 4
for number in range(5):
print("Hello!")
Let's break down the syntax:
for: The keyword that starts the loop.number: A temporary variable that holds the current item from the sequence in each iteration.in: The keyword that separates the variable from the sequence.range(5): The sequence to iterate over.:: The colon at the end of the line is required.print("Hello!"): This is the block of code to be executed. Note that it's indented, which is how Python knows it's inside the loop.
You can also use the temporary variable inside the loop.
# We can use the 'number' variable inside the loop
for number in range(5):
print(f"The current number is {number}")
For loops can also iterate over other types of sequences, like the characters in a string.
for character in "Python":
print(character)
The While Loop
What if you don't know how many times you need to loop? What if you just want to repeat an action until a certain condition is met? That's where the while loop comes in.
A while loop repeatedly executes a block of code as long as a specified condition is True. Think of it like a guard at a gate who keeps letting people through as long as they have a ticket.
count = 0
while count < 3:
print(f"The count is {count}")
count = count + 1 # Crucial step!
print("Loop finished!")
In this example:
- We start with a variable
countset to 0. - The
whileloop checks ifcount < 3. Since 0 is less than 3, the condition isTrue, and the code inside the loop runs. - It prints the value of
count. - It then increments
countby 1. This is the most important part! Without it,countwould always be 0, the condition would always beTrue, and the loop would run forever.
This process repeats until count becomes 3. At that point, the condition count < 3 is False, and the loop stops. The program then moves on to the next line of code outside the loop.
| Loop Type | When to Use It |
|---|---|
for | When you have a sequence or know the number of iterations. |
while | When you want to loop until a specific condition is met. |
Loops are powerful tools for making your programs efficient and dynamic. Understanding when and how to use for and while loops is a key step in becoming a proficient programmer.