Repeat once per item
prices = [120, 340, 90, 75]
for price in prices:
print(price)Read it as an English sentence: for each price in prices, print the price. Python takes the first item, attaches the name price to it, runs the indented block, then takes the second item, and so on until the list runs out.
price is a name you chose. It could be p or amount. It only exists because you named it in the for line, and it gets re-attached to a new value on every pass.
The indentation is the loop body
Python uses indentation the way other languages use braces. Whatever is indented under the for line runs every pass. Whatever is not, runs once, after the loop is done.
for price in prices:
print("item", price)
print("done")done prints once. Move it four spaces to the right and it prints four times. Use four spaces, be consistent, and let your editor do it for you. Mixing tabs and spaces produces IndentationError or, worse, code that runs and means something you did not intend.
The accumulator
The most useful pattern in beginner programming: start with an empty answer, add to it on every pass, look at it at the end.
prices = [120, 340, 90, 75]
total = 0
for price in prices:
total = total + price
print(total) # 625The line total = 0 is outside the loop, and this is the whole trick. It has to happen once, before any adding starts. Put it inside the loop and it happens on every pass, wiping out the running total each time, and the answer becomes the last item instead of the sum. That bug produces no error and looks almost identical on screen.
total = total + price can be shortened to total += price. Same thing.
The same pattern builds lists:
doubled = []
for price in prices:
doubled.append(price * 2)
print(doubled) # [240, 680, 180, 150]Counting with range
When you want to do something a fixed number of times rather than once per item:
for i in range(3):
print("attempt", i)attempt 0
attempt 1
attempt 2range(3) gives 0, 1, 2. Three numbers, starting at zero, stopping before three. range(1, 4) gives 1, 2, 3. The stop value is never included, which is deliberate: range(len(prices)) then lines up exactly with the valid positions.
Looping over a dict
student = {"name": "Amara", "city": "Kano", "marks": 81}
for key in student:
print(key, "->", student[key])
for key, value in student.items():
print(key, "->", value)Both print the same thing. .items() hands you the key and the value together, which is usually what you wanted.
while, for when you do not know how many
balance = 5000
months = 0
while balance > 0:
balance = balance - 1200
months = months + 1
print(months, "months") # 5 monthswhile repeats as long as its condition is true, and checks the condition before each pass. If nothing inside ever makes the condition false, the program runs forever; press Ctrl+C to stop it. Reach for for first. Use while when the number of passes depends on what happens inside.
Try this now
marks = [78, 81, 45, 92, 60]
passed = []
for m in marks:
if m >= 50:
passed.append(m)
print(passed)
print(f"{len(passed)} of {len(marks)} passed")
print(f"average {sum(marks) / len(marks)}")Before you move on