Going through a list with for
Lists are made to be gone through: print every price, add up every score, check every name. Python has a loop made for exactly this job, the for loop:
prices = [12, 5, 30]
for price in prices:
print(price)
12
5
30Read it as "for each price in prices". In the first round, the variable after for (here price) is the first item, 12, and the indented block runs with it. In the next round price is 5, and in the last one 30. After the last item, the loop is over and the program goes on with the line after it.
The variable can have any name. Choose one that says what an item is: for price in prices, for name in names.
With only while, the same job takes a counter of your own:
index = 0
while index < len(prices):
print(prices[index])
index += 1
That's four lines instead of two, and three chances to slip: start the counter at the wrong number, write <= where < belongs, or forget index += 1 and loop forever. A for loop has no counter, so none of those mistakes can happen.
Definite and indefinite loops
A while loop repeats as long as its condition is true, and you can't always tell in advance how many rounds that will be: it might wait for the user to type quit. That's called indefinite iteration. A for loop goes through a collection that's already there, so the number of rounds is known when it starts: one per item. That's definite iteration.
Working with each item
Most loops do more than print. A helper variable before the loop collects a result while the loop goes through the items:
prices = [12, 5, 30, 8]
total = 0
cheap = 0
for price in prices:
total += price
if price < 10:
cheap += 1
print("Total:", total)
print("Under 10:", cheap)
Total: 55
Under 10: 2sum(prices) would give the total too, but the loop can do anything with each item: here it also counts the cheap ones, which no ready function does.
Inside a function, a return in the loop ends the whole function at once. Put the return after the loop (not indented under it) when the function needs to see every item first.