Workshop: Loops and Comprehensions (Optional, Self-Study)¶
View workshop code on GitHub Get the Video Course
From the lesson
Workshop problems for Section 06 Concepts. Build each yourself first, then expand the solution to check.
Seven optional workshop problems, one per concept step: the same ideas as the lesson, in a car scenario, so you apply each idea instead of copying the demo. The numbers line up with the steps (Workshop-01 goes with Step-01).
These are self-study (not live-coded). The stub files in this folder say WHAT to do; you write the code, then check the matching file in python-workshop/solutions. Recommended, but your choice.
Step-01: while Loops¶
Concepts: while loop, counting down, the -= shorthand, a truthy condition.
Write a program that, for a car:
- Task-1: starting with
4units of fuel, uses awhileloop to print the fuel left each turn (likeFuel left: 4) as it drops to1, burning1unit each turn, then printsTank empty. - Task-2: for a boot holding the items
bag,box,cooler, useswhile items:(a non-empty list is truthy) to print the last item and remove it, until the boot is empty.
Need a hint?
Decrease the fuel variable with -= inside the while loop so the condition eventually turns False, then print("Tank empty"). For Task-2, while items: stays true while the list has items; items.pop() removes AND returns the last one, so the list empties.
Show the solution
# Task-1: count the fuel down with -= until the tank is empty
fuel = 4
while fuel >= 1:
print("Fuel left:", fuel)
fuel -= 1
print("Tank empty")
# Task-2: loop while the list is non-empty (truthy); pop() removes and returns the last item
items = ["bag", "box", "cooler"]
while items:
print(items.pop())
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-02: for Loops¶
Concepts: for loop, a running total, counting with if, unpacking a tuple in the loop.
Write a program that, for a car lot with the prices 15000, 8000, 23000, 12000:
- Task-1: print each price on its own line with a
forloop. - Task-2: print
total:followed by the sum of the prices. - Task-3: print
over 10000:followed by how many cars cost more than10000(count with afor+if). - Task-4: for a list of
(brand, price)pairs("Audi", 40000)and("BMW", 8000), unpack each pair in theforheader and printbrand: price.
Need a hint?
Accumulate a total in the for loop and count the cars over 10000 with a separate counter (add 1 inside an if). For Task-4, unpack each pair with for brand, price in cars.
Show the solution
# one pass prints each price and adds it to the running total
prices = [15000, 8000, 23000, 12000]
total = 0
# Task-1: print each price with a for loop
for price in prices:
print(price)
total += price
# Task-2: print the total of the prices
print("total:", total)
# Task-3: count the cars over 10000 with a for + if
over = 0
for price in prices:
if price > 10000:
over += 1
print("over 10000:", over)
# Task-4: unpack each (brand, price) pair right in the for header
cars = [("Audi", 40000), ("BMW", 8000)]
for brand, price in cars:
print(f"{brand}: {price}")
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-03: range()¶
Concepts: for loop, range(), the step argument (including a negative step), list(range(...)), f-strings.
Write a program that, for a car serviced every 10000 km:
- Task-1: loop over the first
5service numbers withrange(1, 6)and print each milestone likeService 1: 10000 km. - Task-2: then count DOWN the services left before a major overhaul, from
5to1, withrange(5, 0, -1)(a negative step), printingCountdown: 5down toCountdown: 1, then printService dueonce after the loop. - Task-3: print
list(range(1, 6))to preview the service numbers as a real list (arangeis lazy until you wrap it inlist()).
Service 1: 10000 km
Service 2: 20000 km
Service 3: 30000 km
Service 4: 40000 km
Service 5: 50000 km
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Service due
[1, 2, 3, 4, 5]
Need a hint?
Loop range(1, 6) and multiply the service number by 10000 in an f-string for the schedule; for the countdown use range(5, 0, -1) (a negative step) and print Service due once after that loop. For Task-3, list(range(1, 6)) turns the lazy range into a real list to preview.
Show the solution
# Task-1: forward service schedule with range(1, 6)
for i in range(1, 6):
print(f"Service {i}: {i * 10000} km")
# Task-2: count DOWN with a negative step, then print once after the loop
for n in range(5, 0, -1):
print(f"Countdown: {n}")
print("Service due")
# Task-3: a range is lazy, so wrap it in list() to preview the numbers
print(list(range(1, 6)))
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-04: break, continue, pass, and else¶
Concepts: for loop, continue, break, loop else, pass, a while loop with break.
Write a program that, for a lot with the prices 30000, 0, 18000, 9000, 25000 (a 0 means the car is sold) and a budget of 12000:
- Task-1: skip any sold car and at the first car within budget (
12000or less) printBuying at:followed by that price and stop looking; if no car fits, printNothing in budgetinstead. - Task-2: loop the same prices again and, for a sold car (
0), do nothing yet withpass(a placeholder branch for logic you add later); for every other car printAvailable:followed by its price. - Task-3: starting with
5units of fuel, use awhileloop to printfuel: Fand burn1unit each check, butbreakthe instant the gauge reads2, printinglow fuel, stopping. - Task-4: starting with
3units of fuel, printfuel: Fand burn1unit each turn, with anelseon thewhilethat printsmade it home. Nobreakfires this time, so theelseruns. Compare with Task-3.
Buying at: 9000
Available: 30000
Available: 18000
Available: 9000
Available: 25000
fuel: 5
fuel: 4
fuel: 3
low fuel, stopping
fuel: 3
fuel: 2
fuel: 1
made it home
Need a hint?
Use continue to skip a 0 (sold) and break at the first price <= 12000; the loop else covers the no-match case. For Task-2, a sold car (0) hits pass (does nothing) while every other car prints Available:. For Task-3, a while loop prints the fuel and breaks the moment it reads 2.
Show the solution
# Task-1: first affordable car with continue / break / else
prices = [30000, 0, 18000, 9000, 25000]
budget = 12000
for price in prices:
if price == 0:
continue # car already sold; skip it
if price <= budget:
print("Buying at:", price)
break
else:
print("Nothing in budget")
# Task-2: list available cars; a sold car (0) hits pass, which does nothing
for price in prices:
if price == 0:
pass # placeholder: nothing to do for a sold car yet
else:
print("Available:", price)
# Task-3: check the fuel gauge with a while loop, break the instant it reads low
fuel = 5
while fuel > 0:
if fuel == 2:
print("low fuel, stopping")
break
print("fuel:", fuel)
fuel -= 1
# Task-4: no break fires, so the while else runs: compare with Task-3, where the break skipped it
fuel = 3
while fuel > 0:
print("fuel:", fuel)
fuel -= 1
else:
print("made it home")
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-05: enumerate, zip, and Looping a Dictionary¶
Concepts: enumerate(start=1), looping a dict with .items(), f-strings.
Problem-1
Write a program that, for a list of cars Audi, BMW, Kia, uses enumerate(start=1) to print each car with its position from 1, like 1. Audi.
Need a hint?
enumerate(cars, start=1) numbers the cars from 1 without a manual counter.
Show the solution
Problem-2
Write a program that, for a dict of brand to price Audi set to 40000, BMW set to 50000, and Kia set to 25000, loops it with .items() and prints each pair like Audi: 40000, then prints total: followed by the sum of every price using .values().
Need a hint?
Loop the dict with .items() to unpack brand, price in the for header; then total the prices with a running total over .values() (total = 0, then total += price).
Show the solution
# Problem-2 Task-1: print each brand and price with .items()
prices = {"Audi": 40000, "BMW": 50000, "Kia": 25000}
for brand, price in prices.items():
print(f"{brand}: {price}")
# Problem-2 Task-2: total every price with a running total over .values()
total = 0
for price in prices.values():
total += price
print("total:", total)
Problem-3: Pair Cars With Prices (zip).
Write a program that, for brands holding "Honda" and "Mazda" and prices holding 20000 and 25000, loops over both lists together with zip() and prints each pair like Honda: 20000.
Need a hint?
zip(brands, prices) pairs the two lists by position so you can print each brand: price.
Show the solution
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-06: Nested Loops¶
Concepts: nested loops, range(), break inside nesting, f-strings.
Write a program that, for a car park:
- Task-1: with
3rows and2columns, use an outerforloop over the rows (1to3) and an innerforloop over the columns (1to2) to print every spot asR<row>C<col>, likeR1C1. - Task-2: scan each of the
3rows across columns1to3, printingscan R<row>C<col>, butbreakat the first blocked spot (column2) so each row stops after column1, while the outer row loop still visits every row.
range() stops one before the end
For rows 1 to 3, use range(1, 4), not range(1, 3). The stop value is never reached, so the stop must be one past the last number you want.
Need a hint?
Nest a column range(1, 3) loop inside a row range(1, 4) loop; the stop value is one past the last row/column you want. For Task-2, break inside the inner loop stops only that row scan - the outer row loop keeps going.
Show the solution
# Task-1: print every parking spot with a nested range x range grid
for row in range(1, 4):
for col in range(1, 3):
print(f"R{row}C{col}")
# Task-2: scan each row but break at the first blocked spot (col 2); outer loop still advances
for row in range(1, 4):
for col in range(1, 4):
if col == 2:
break
print(f"scan R{row}C{col}")
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Step-07: Comprehensions¶
Concepts: list comprehension, a filter condition, dict comprehension (plain and filtered), set comprehension, an if/else in a comprehension.
Problem-1: Car Price Lists.
Write a program that:
- Task-1: for the prices
15000,8000,23000, use a list comprehension to print a list of each price plus500. - Task-2: for the same prices, use a list comprehension and a filter to print a list of only the prices over
10000. - Task-3: for the cars
Audi,BMW,Kia, use a dict comprehension to print a dict mapping each car to the length of its name. - Task-4: with a dict comprehension and a filter, map only the prices over
10000to their discounted value (price - 1000). - Task-5: for the same cars, use a set comprehension to print the sorted list of distinct name lengths.
- Task-6: with an
if/elsein a list comprehension, label each price"premium"(10000 or more) or"budget".
[15500, 8500, 23500]
[15000, 23000]
{'Audi': 4, 'BMW': 3, 'Kia': 3}
{15000: 14000, 23000: 22000}
[3, 4]
['premium', 'budget', 'premium']
Need a hint?
Use [p + 500 for p in prices], add if p > 10000 to filter, {car: len(car) for car in cars} for the dict (a trailing if filters it too), {len(car) for car in cars} for a set of distinct lengths (sort it), and ["premium" if p >= 10000 else "budget" for p in prices] for the if/else.
Show the solution
prices = [15000, 8000, 23000]
# Task-1: print each price plus 500 with a list comprehension
print([p + 500 for p in prices])
# Task-2: print only the prices over 10000 with a filter
print([p for p in prices if p > 10000])
cars = ["Audi", "BMW", "Kia"]
# Task-3: map each car to the length of its name with a dict comprehension
print({car: len(car) for car in cars})
# Task-4: a dict comprehension can filter too: only prices over 10000, discounted
print({p: p - 1000 for p in prices if p > 10000})
# Task-5: a set comprehension drops duplicate name lengths (sort it, a set is unordered)
print(sorted({len(car) for car in cars}))
# Task-6: an if/else inside the comprehension labels each price
print(["premium" if p >= 10000 else "budget" for p in prices])
Problem-2: Discount With A Comprehension.
Write a program that, for prices holding 100 and 200, uses a list comprehension to take 10% off each price (multiply by 0.9) and prints the resulting list.
Need a hint?
Multiply each price by 0.9 in a comprehension; the result is floats like 90.0 because 0.9 is a float.
Show the solution
Pages for this step: Concept | Practice | Workshop
Python Files for this step: Concept | Practice | Practice Solutions | Workshop | Workshop Solutions
Finished this section?
Check your work against the solutions above, then head back to the Section 06 lesson, or try the Section 06 practice for more reps.
Prefer to learn by watching?
The full video course teaches every concept on screen and builds the projects with you, step by step.
Workshop: Collections Next: Workshop: Functions