Python lesson
Loops with if
The loop visits 70, 15, 24 and 140. Only 70 and 140 pass the test, so only they are printed. The print is indented twice: it's inside the if, which is inside the loop.
Try this lesson free →Example
Put an if inside a loop, and the test runs once for every item:
orders = [70, 15, 24, 140]
for o in orders:
if o > 50:
print(o)70
140Key points
for o in orders:The loop visits every item.
if o > 50:Inside the loop, the test runs for each item.
print(o)Indented twice: only runs when the test is True for that item.
Indentation shows what's inside what: the if is inside the loop, and the print is inside the if.
Practice
1. Build a loop that prints only the orders over 50.
for o in orders:
if o > 50:
print(o)2. Build a loop that prints only the orders under 20.
for o in orders:
if o < 20:
print(o)3. Build a loop that counts how many sales are over 100, then shows the count.
for s in sales:
if s > 100:
count = count + 1
print(count)4. Loop through orders and print only the ones over 50.
orders = [70, 15, 24, 140, 30, 105]
for o in orders:
if o > 50:
print(o)5. Print every product that isn't Charger.
products = ["Earbuds", "Charger", "Cable", "Charger"]
for p in products:
if p != "Charger":
print(p)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 →