For-loops in Python#
This notebook introduces the concept of for-loops in Python, a fundamental tool for iterating over sequences and performing repetitive tasks efficiently.
Let’s start with a simple for-loop that iterates over a list of numbers. This demonstrates the basic syntax of a for-loop in Python.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
1
2
3
4
5
We can also use the range()
function to generate a sequence of numbers to iterate over. This is useful when you want to repeat an action a specific number of times.
for i in range(5):
print(f"Iteration {i+1}")
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
For-loops can be used with strings to iterate over each character. This is helpful for tasks like counting specific characters or performing operations on each character.
word = "Python"
for char in word:
print(char.upper())
P
Y
T
H
O
N
We can use the enumerate()
function with a for-loop to get both the index and the value of each item in a sequence. This is particularly useful when you need to track the position of items.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Index 0: apple
Index 1: banana
Index 2: cherry
For-loops can also be used with dictionaries. By default, looping over a dictionary iterates over its keys. We can use the .items()
method to iterate over both keys and values.
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
name: Alice
age: 30
city: New York
Finally, let’s look at a practical example where we use a for-loop to calculate the sum of numbers in a list. This demonstrates how loops can be used for data processing tasks.
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"The sum of the numbers is: {total}")
The sum of the numbers is: 150