Skip to content

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 4 units of fuel, uses a while loop to print the fuel left each turn (like Fuel left: 4) as it drops to 1, burning 1 unit each turn, then prints Tank empty.
  • Task-2: for a boot holding the items bag, box, cooler, uses while items: (a non-empty list is truthy) to print the last item and remove it, until the boot is empty.
Expected output
Fuel left: 4
Fuel left: 3
Fuel left: 2
Fuel left: 1
Tank empty
cooler
box
bag
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
s06_workshop01_sol_while_loops.py
# 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())

View the full solution file on GitHub

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 for loop.
  • Task-2: print total: followed by the sum of the prices.
  • Task-3: print over 10000: followed by how many cars cost more than 10000 (count with a for + if).
  • Task-4: for a list of (brand, price) pairs ("Audi", 40000) and ("BMW", 8000), unpack each pair in the for header and print brand: price.
Expected output
15000
8000
23000
12000
total: 58000
over 10000: 3
Audi: 40000
BMW: 8000
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
s06_workshop02_sol_for_loops.py
# 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}")

View the full solution file on GitHub

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 5 service numbers with range(1, 6) and print each milestone like Service 1: 10000 km.
  • Task-2: then count DOWN the services left before a major overhaul, from 5 to 1, with range(5, 0, -1) (a negative step), printing Countdown: 5 down to Countdown: 1, then print Service due once after the loop.
  • Task-3: print list(range(1, 6)) to preview the service numbers as a real list (a range is lazy until you wrap it in list()).
Expected output
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
s06_workshop03_sol_range.py
# 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)))

View the full solution file on GitHub

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 (12000 or less) print Buying at: followed by that price and stop looking; if no car fits, print Nothing in budget instead.
  • Task-2: loop the same prices again and, for a sold car (0), do nothing yet with pass (a placeholder branch for logic you add later); for every other car print Available: followed by its price.
  • Task-3: starting with 5 units of fuel, use a while loop to print fuel: F and burn 1 unit each check, but break the instant the gauge reads 2, printing low fuel, stopping.
  • Task-4: starting with 3 units of fuel, print fuel: F and burn 1 unit each turn, with an else on the while that prints made it home. No break fires this time, so the else runs. Compare with Task-3.
Expected output
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
s06_workshop04_sol_break_continue.py
# 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")

View the full solution file on GitHub

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.

Expected output
1. Audi
2. BMW
3. Kia
Need a hint?

enumerate(cars, start=1) numbers the cars from 1 without a manual counter.

Show the solution
s06_workshop05_sol_enumerate_and_dict.py
# Problem-1 Task-1: number each car with enumerate
cars = ["Audi", "BMW", "Kia"]
for position, car in enumerate(cars, start=1):
    print(f"{position}. {car}")

View the full solution file on GitHub

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().

Expected output
Audi: 40000
BMW: 50000
Kia: 25000
total: 115000
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
s06_workshop05_sol_enumerate_and_dict.py
# 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)

View the full solution file on GitHub

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.

Expected output
Honda: 20000
Mazda: 25000
Need a hint?

zip(brands, prices) pairs the two lists by position so you can print each brand: price.

Show the solution
s06_workshop05_sol_enumerate_and_dict.py
# Problem-3 Task-1: pair each car with its price using zip
brands = ["Honda", "Mazda"]
prices = [20000, 25000]
for brand, price in zip(brands, prices):
    print(f"{brand}: {price}")

View the full solution file on GitHub

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 3 rows and 2 columns, use an outer for loop over the rows (1 to 3) and an inner for loop over the columns (1 to 2) to print every spot as R<row>C<col>, like R1C1.
  • Task-2: scan each of the 3 rows across columns 1 to 3, printing scan R<row>C<col>, but break at the first blocked spot (column 2) so each row stops after column 1, while the outer row loop still visits every row.
Expected output
R1C1
R1C2
R2C1
R2C2
R3C1
R3C2
scan R1C1
scan R2C1
scan R3C1

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
s06_workshop06_sol_nested_loops.py
# 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}")

View the full solution file on GitHub

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 plus 500.
  • 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 10000 to 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/else in a list comprehension, label each price "premium" (10000 or more) or "budget".
Expected output
[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
s06_workshop07_sol_comprehensions.py
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])

View the full solution file on GitHub

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.

Expected output
[90.0, 180.0]
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
s06_workshop07_sol_comprehensions.py
# Problem-2 Task-1: take 10% off each price with a comprehension
prices = [100, 200]
print([p * 0.9 for p in prices])

View the full solution file on GitHub

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.

Get the Video Course

Workshop: Collections Next: Workshop: Functions

🎉 New Course
Python for Absolute Beginners
$15.99 $84.99 81% OFF
Get the Video Course