Python lesson
Loops, step 1
Read it as: for each s in sales, print s. The first time round, s is 96. The second time, 120. Then 175. Three items, so the indented line runs three times.
Try this lesson free →Example
A for loop takes each item in a list, one at a time, and runs the indented lines for it:
sales = [96, 120, 175]
for s in sales:
print(s)96
120
175Key points
for s in sales:Take each item in turn and call it s. The line ends with a colon.
print(s)Indented by 4 spaces: this runs once for every item.
sYou choose the name. It holds the current item each time round.
Python knows which lines repeat because they're indented. Lines that aren't indented run once.
Practice
1. Build the first line of a loop over prices.
for p in prices:2. Build the indented line that shows each price doubled.
print(p * 2)3. Print each sale on its own line, using a for loop.
sales = [96, 120, 175, 120, 100]
for s in sales:
print(s)4. Print each product name in capitals, using a for loop.
products = ["Earbuds", "Charger", "Cable"]
for p in products:
print(p.upper())5. Print each day followed by the word done, like Mon done.
days = ["Mon", "Tue", "Wed"]
for d in days:
print(f"{d} done")Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →