Part 03 / Topic 6 of 12
for loop
for takes each item from a collection (a list, a string, a range ...) one by one, like a cashier scanning each item in your basket. Use for when you know what to loop over; use while when you loop until something happens.
A list is a group of values inside square brackets, like ["Tea", "Samosa"]. You will learn lists properly in Part 4.
Real-world example: print a bill for each item.
items = ["Tea", "Samosa", "Vada Pav"]
for item in items:
print(f"- {item}")
# - Tea
# - Samosa
# - Vada Pav
for letter in "UPI":
print(letter, end=" ")
print()
# U P I
| Use | Loop |
|---|---|
| Go over every item of a list / string | for |
| Repeat N times | for i in range(N) |
| Repeat until a condition changes (unknown count) | while |
๐ Going deeper:
forworks on any iterable: anything that can hand out items one at a time (lists, strings,range, dicts, files ...). If the loop ran at least once, the loop variable still exists after the loop ends, holding the last item. If the loop never ran (an empty list), the loop does not create the variable, so using it can give aNameError.
Done here? The practice set for Part 3 โ 7 exercises with solutions โ is on the part page.