Previous chapter | Next Chapter |
---|---|
Python Chapter 1: Getting started | Python Chapter 3: Understanding Functions |
Now that you’re familiar with basic Python syntax, let’s dive into one of the most powerful tools in programming: loops. Loops allow you to repeat actions multiple times without writing the same code over and over. In Python, the two main types of loops are for
and while
.
1. The for
Loop
A for
loop lets you iterate over a sequence (like a list, string, or range of numbers). This is useful when you want to execute a block of code a specific number of times or for each item in a collection.
Example:
for number in range(5):
print(number)
In this example, the range(5)
generates numbers from 0
to 4
, and the loop prints each number one by one.
Looping through a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This loop prints each fruit in the list.
2. The while
Loop
A while
loop repeats as long as a condition is True
. Be careful with while
loops, though—they can run forever if the condition never becomes False
.
Example:
count = 0
while count < 5:
print(count)
count += 1
In this loop, as long as count
is less than 5
, it will print the value of count
and increase it by 1
after each iteration.
3. Loop Control Statements
Sometimes, you may want more control over your loops. Python provides special statements like break
, continue
, and pass
to control how the loop behaves.
break
: Exits the loop completely.continue
: Skips the current iteration and moves to the next one.pass
: Does nothing; it’s a placeholder when a statement is required syntactically but you don’t want any action.
Example of break
:
for number in range(10):
if number == 5:
break # Loop stops when number is 5
print(number)
Example of continue
:
for number in range(10):
if number % 2 == 0:
continue # Skip even numbers
print(number)
Example of pass
:
for number in range(5):
if number == 3:
pass # Do nothing when number is 3
else:
print(number)
4. Nested Loops
You can place one loop inside another. These are called nested loops. They are useful when you want to work with multidimensional data or perform more complex tasks.
Example:
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop runs twice.
By mastering loops, you’ve unlocked the ability to handle repetitive tasks efficiently. Practice using for
and while
loops, and don’t forget to experiment with control statements to make your code even more flexible. Next, we’ll explore how to organize your code using functions!