for loops
A for loop goes through the items of a collection one at a time. It is the loop you will use most in Python.
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)Each time round, the loop variable (fruit) refers to the next item. When the items run out, the loop ends; there is no counter to manage.
Looping over a string
A string is a sequence of characters, so you can loop over it too:
Python
for letter in "Python":
print(letter)Keeping a running total
Python
prices = [120, 45, 300, 15]
total = 0
for price in prices:
total += price
print("Total:", total)Counting matches
Python
words = ["apple", "avocado", "banana", "apricot", "cherry"]
count = 0
for word in words:
if word.startswith("a"):
count += 1
print(count, "words start with 'a'")enumerate(): the position and the item
When you need the index as well as the value, use enumerate():
Python
players = ["Asha", "Leo", "Mei"]
for position, name in enumerate(players, start=1):
print(f"{position}. {name}")This is much cleaner than keeping your own counter.
zip(): two lists side by side
zip() pairs up items from several collections:
Python
names = ["Asha", "Leo", "Mei"]
scores = [92, 78, 85]
for name, score in zip(names, scores):
print(f"{name}: {score}")zip stops when the shortest collection runs out.
for vs while
- Use for when you are going through a collection or a known number of steps.
- Use while when you repeat until something happens and don't know how many times that will take.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.