Python For Loops
The for
loop in Python is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). It's more like an iterator method than a traditional for
loop.
Example 1: Looping Through a List
Print each name in a list of names.
# Looping through a list
names = ["Karthick AG", "Vijay", "John", "Durai"]
for name in names:
print("Hello,", name + "!")
Hello, Karthick AG!
Hello, Vijay!
Hello, John!
Hello, Durai!
Example 2: Looping Through a String
Print each character in a string.
# Looping through a string
language = "Tamil"
for letter in language:
print(letter)
T
a
m
i
l
Example 3: Using range()
Function
Print numbers from 1 to 5 using range()
.
# Using range()
for number in range(1, 6):
print("Number:", number)
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 4: Nested For Loops
Print all combinations of names and cities.
# Nested for loops
names = ["Rudra", "Riya"]
cities = ["Trichy", "Karur"]
for name in names:
for city in cities:
print(f"{name} lives in {city}.")
Rudra lives in Trichy.
Rudra lives in Karur.
Riya lives in Trichy.
Riya lives in Karur.
Example 5: Looping Through a Dictionary
Print keys and values from a dictionary of freedom fighters.
# Looping through a dictionary
freedom_fighters = {
"Velu Nachiyar": "Sivaganga",
"V. O. Chidambaram Pillai": "Ottapidaram",
"Subramania Bharathi": "Ettayapuram"
}
for name, place in freedom_fighters.items():
print(f"{name} from {place}.")
Velu Nachiyar from Sivaganga.
V. O. Chidambaram Pillai from Ottapidaram.
Subramania Bharathi from Ettayapuram.
Explanation: The for
loop is used to iterate over sequences. The range()
function generates a sequence of numbers, and nested loops can be used to perform complex iterations.