What You Will Learn
Beginner
- How to use for loops
- Iterating over lists, strings, and ranges
- Common loop patterns
Terminalpython
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Hello":
print(char)
# Using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step=2)
print(i)Iterating Over Dictionaries
Terminalpython
person = {"name": "Anita", "age": 28, "city": "Mumbai"}
# Keys only
for key in person:
print(key)
# Keys and values
for key, value in person.items():
print(f"{key}: {value}")
# Values only
for value in person.values():
print(value)enumerate() - Get Index and Value
Terminalpython
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherryPractical Exercise
Loop over [10, 20, 30, 40] and print each
Loop over range(1, 11) and print squares: i*i
Use enumerate to print index and value of a list
Loop over a dictionary and print key: value
Key Takeaways
- for loops iterate over any sequence (list, string, range, dict).
- range(n) = 0 to n-1. range(a, b) = a to b-1.
- range(start, stop, step) for custom steps.
- enumerate() gives index + value.
- dict.items() for key-value pairs.
Comments
Comments
Post a Comment