So far, we've learned how to execute code line by line and how to make simple decisions using if statements. But what if you need to perform an action multiple times? This is where loops come in! Loops are fundamental to programming as they allow us to automate repetitive tasks, saving us a tremendous amount of time and effort.
Python offers two primary types of loops: the for loop and the while loop. Each has its own strengths and is suited for different scenarios.
The for loop is designed to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in that sequence. It's perfect when you know exactly how many times you want to repeat an action, or when you want to process each element of a collection.
The general syntax for a for loop looks like this:
for item in sequence:
# Code to be executed for each itemLet's break this down:
for: This keyword initiates the loop.item: This is a variable that will take on the value of each element in thesequenceone by one during each iteration.in: This keyword connects theitemto thesequence.sequence: This is the iterable object (like a list or a string) that the loop will go through.- The colon
:marks the end of theforstatement and the beginning of the indented code block that will be repeated.
Here's a simple example using a list of fruits:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)When you run this code, it will output: apple banana cherry
Notice how the print(fruit) statement is executed once for each element in the fruits list, with the fruit variable holding the current element during each iteration.
The range() function is particularly useful with for loops, as it generates a sequence of numbers. It's commonly used when you need to repeat an action a specific number of times.
Syntax for range():
range(stop): Generates numbers from 0 up to (but not including)stop.range(start, stop): Generates numbers fromstartup to (but not including)stop.range(start, stop, step): Generates numbers fromstartup to (but not including)stop, incrementing bystep.
for i in range(5):
print(i)This will output: 0 1 2 3 4
for num in range(2, 10, 2):
print(num)This will output: 2 4 6 8
The while loop is different from the for loop because it repeats a block of code as long as a specified condition remains true. This is useful when you don't know in advance how many times the loop needs to run, but you have a condition that will eventually become false.
The general syntax for a while loop:
while condition:
# Code to be executed as long as the condition is trueLet's break this down:
while: This keyword initiates the loop.condition: This is a boolean expression that is evaluated before each iteration. If it'sTrue, the code block inside the loop is executed. If it'sFalse, the loop terminates.- The colon
:marks the end of thewhilestatement and the beginning of the indented code block.
Here's an example of a while loop:
count = 0
while count < 5:
print(count)
count += 1 # This is crucial to eventually make the condition falseThis will produce the same output as the range(5) example:
0
1
2
3
4
It's absolutely vital that the condition in a while loop eventually becomes False. If the condition never becomes False, you'll create an infinite loop, which will cause your program to run forever (or until you manually stop it). In the example above, count += 1 increments the count variable, ensuring it will eventually reach 5 and the while condition (count < 5) will become False.
graph TD
A[Start]
B{Condition True?}
C[Execute Code Block]
D[Update Condition Variable]
E[End]
A --> B
B -- Yes --> C
C --> D
D --> B
B -- No --> E
Sometimes, you might want to alter the normal flow of a loop. Python provides two keywords for this: break and continue.
break: Exits the loop entirely, even if the loop's condition is still true or there are more items to process in aforloop.continue: Skips the rest of the current iteration and moves to the next one. The loop's condition is re-evaluated.
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number == 4:
break # Exit the loop when we reach 4
print(number)Output: 1 2 3
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number == 4:
continue # Skip printing when we reach 4
print(number)Output: 1 2 3 5 6
Understanding and effectively using loops is a major step in becoming a proficient Python programmer. They are the workhorses of automation, allowing you to tackle complex tasks with elegant and concise code.