Mastering the Python for Loop
Mastering the Python for Loop ๐ก
The for loop is one of the most commonly used features in Python for iterating over lists, tuples, dictionaries, and other iterable objects. Let's go over some practical examples.
✅ Iterating over a list
Use a for loop to process each element in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
✅ Using range() for index-based loops
If you need to loop a specific number of times, use range():
for i in range(3):
print(f"Index {i}")
✅ Looping through dictionaries
Access both keys and values easily using the .items() method:
users = {"Alice": 25, "Bob": 30}
for name, age in users.items():
print(f"{name} is {age} years old")
The for loop is clean, powerful, and readable. It should be your go-to for repetitive tasks in Python!
Master the basics, and the rest will follow. Grow your coding skills daily with CodeVerse ๐
Icons by Flaticon
Comments
Post a Comment