In Python, the for loop is a control flow statement used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. The for loop allows you to execute a block of code for each element in the sequence.
Basic Structure
The basic structure of a for loop is as follows:
for variable in iterable:
# Code block to execute for each element
- variable: This is a variable that takes the value of the item inside the iterable on each iteration.
- iterable: This can be any Python object that can return its elements one at a time, such as a list, tuple, string, etc.
Examples of Using for Loops
Iterating Over a List
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Iterating Over a String
for char in "hello":
print(char)
# Output:
# h
# e
# l
# l
# o
Using range() Function
The range() function generates a sequence of numbers. It's commonly used with for loops to iterate over a sequence of numbers.
# Iterating over a range of numbers from 0 to 4
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
# Iterating with a starting and ending point
for i in range(2, 6):
print(i)
# Output:
# 2
# 3
# 4
# 5
# Iterating with a step
for i in range(1, 10, 2):
print(i)
# Output:
# 1
# 3
# 5
# 7
# 9
Iterating Over a Dictionary
When iterating over a dictionary, you can iterate over keys, values, or key-value pairs.
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Iterating over keys
for key in person:
print(key)
# Output:
# name
# age
# city
# Iterating over values
for value in person.values():
print(value)
# Output:
# Alice
# 30
# New York
# Iterating over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 30
# city: New York
Using for Loop with else
An optional else block can follow a for loop. The else block executes only if the loop completes normally, without encountering a break statement.
for i in range(5):
print(i)
else:
print("Loop completed without break.")
# Output:
# 0
# 1
# 2
# 3
# 4
# Loop completed without break.
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed without break.")
# Output:
# 0
# 1
# 2
In this example, the else block is not executed because the loop was terminated with a break.
Nested for Loops
You can nest for loops to iterate over multiple sequences.
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
# Output:
# i = 0, j = 0
# i = 0, j = 1
# i = 1, j = 0
# i = 1, j = 1
# i = 2, j = 0
# i = 2, j = 1
Using for Loop with enumerate()
The enumerate() function adds a counter to an iterable and returns it as an enumerate object.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
for Loop with zip()
The zip() function takes multiple iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the passed iterables.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
# Output:
# Alice is 25 years old.
# Bob is 30 years old.
# Charlie is 35 years old.
The for loop is a fundamental construct in Python that allows you to iterate over elements of a collection or other iterable objects efficiently. It's commonly used for tasks such as processing data, executing repeated actions, and more.
'Python > Flow control' 카테고리의 다른 글
python flow control - while (0) | 2024.08.10 |
---|---|
python flow control - if statement (0) | 2024.08.03 |