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(f"{o} is big")70 is big
140 is bigKey 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 the test inside the loop: is the order over 50?
if o > 50:2. Build the loop line over the orders list.
for o in orders:3. 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)4. Print every product that isn't Charger.
products = ["Earbuds", "Charger", "Cable", "Charger"]
for p in products:
if p != "Charger":
print(p)5. Count how many orders are over 50 with a loop, then print the count.
orders = [70, 15, 24, 140, 30, 105]
count = 0
for o in orders:
if o > 50:
count = count + 1
print(count)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 →