Skip to content

Practice: Loops and Comprehensions

View practice code on GitHub Get the Video Course

From the lesson

Practice problems for Section 06 Concepts. Build each yourself first, then expand the solution to check.

Seven practice problems, one per concept step, the numbers line up (Practice-01 goes with Step-01, and so on). Build each one yourself in the python-practice folder, then compare with the matching file in python-practice/solutions. Do this before starting the next section.

Each problem lists the concepts it practices and the exact output to aim for. Write the code yourself. The stub files only describe the task, they do not contain the code. Most problems end with a short "Write a Program" exercise that uses input() (some use static data instead).

These problems continue the online-store story: now you process the day's orders. You loop over the cart, total the bills, run comprehensions over prices, and pair up products with their prices.

Step-01: while Loops

Concepts: while loop, counting down, the -= shorthand, a running total, a truthy condition, input().

Problem-1: Pack the Cart.

Write a program that, starting from items_left set to 10, uses a while loop to print items_left on its own line as it counts down to 1, then prints Cart packed!.

Expected output
10
9
8
7
6
5
4
3
2
1
Cart packed!

A while loop needs the counter to change

Inside the while loop you must decrease items_left (with items_left -= 1). If you forget, the condition stays True forever and the loop never stops. Press Ctrl+C to stop a runaway loop.

Need a hint?

A while loop runs as long as its condition is True; decrease items_left with items_left -= 1 each pass so it eventually reaches the stop, then print after the loop.

Show the solution
s06_practice01_sol_while_loops.py
# Problem-1 Task-1: count down items and pack the cart
items_left = 10
while items_left >= 1:
    print(items_left)
    items_left -= 1
print("Cart packed!")

View the full solution file on GitHub

Problem-2: Loyalty Points.

Write a program that adds up loyalty points earned over 5 days (1 point on day 1, 2 on day 2, up to 5 on day 5) into a running total with a while loop, then prints Points: followed by the total.

Expected output
Points: 15
Need a hint?

Start total at 0 and a day counter at 1; add day into total each pass (total += day) and stop after day 5, then print Points: and the total.

Show the solution
s06_practice01_sol_while_loops.py
# Problem-2 Task-1: accumulate the daily points into one running total
total = 0
day = 1
while day <= 5:
    total += day
    day += 1
print("Points:", total)

View the full solution file on GitHub

Problem-3: Empty the Shelf.

Define a variable shelf as a list with the values milk, eggs, bread. Using while shelf: (a non-empty list is truthy), print the last item, then remove it, until the shelf is empty.

Expected output
bread
eggs
milk
Need a hint?

while shelf: is true while the list still has items; shelf.pop() removes AND returns the last item, so the list empties and the loop ends.

Show the solution
s06_practice01_sol_while_loops.py
# Problem-3 Task-1: loop while the list is non-empty (truthy); pop() removes and returns the last item
shelf = ["milk", "eggs", "bread"]
while shelf:
    print(shelf.pop())

View the full solution file on GitHub

Problem-4 (Write a Program): Dispatch Orders.

Write a program that asks the user for a whole number of orders, then counts down from that number to 1 with a while loop and prints All dispatched.

Example run
Orders to dispatch: 3
3
2
1
All dispatched
Need a hint?

Wrap input() in int() first, then drive the same while orders >= 1 countdown using the typed number of orders as the start.

Show the solution
s06_practice01_sol_while_loops.py
# Problem-4 Task-1: count down from the user's order count
orders = int(input("Orders to dispatch: "))
while orders >= 1:
    print(orders)
    orders -= 1
print("All dispatched")

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, len(), split(), for over a string, input().

Problem-1: Total the Bill.

Write a program that, for the order line prices 50, 120, 65, 85:

  • 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 average: followed by the sum divided by the number of prices.
Expected output
50
120
65
85
total: 320
average: 80.0
Need a hint?

Keep a total variable starting at 0 and add each price inside the for loop; divide total by the number of prices for the average.

Show the solution
s06_practice02_sol_for_loops.py
order_prices = [50, 120, 65, 85]
bill = 0
# Problem-1 Task-1: print each price with a for loop
for price in order_prices:
    print(price)
    bill += price
# Problem-1 Task-2: print the total of the prices
print("total:", bill)
# Problem-1 Task-3: print the average price
print("average:", bill / len(order_prices))

View the full solution file on GitHub

Problem-2 (Write a Program): List the Products.

Write a program that asks the user for product names separated by spaces, then uses a for loop to print each product on its own line.

Example run
Enter products separated by spaces: mouse keyboard monitor
mouse
keyboard
monitor
Need a hint?

input().split() returns a list of product names, so a for loop over that list prints one product per line.

Show the solution
s06_practice02_sol_for_loops.py
# Problem-2 Task-1: print each product the user typed
product_line = input("Enter products separated by spaces: ")
for product in product_line.split():
    print(product)

View the full solution file on GitHub

Problem-3: Loop a Product Code.

Define a variable product_code with the value B4X2. Write a program that prints each character of the code on its own line.

Expected output
B
4
X
2
Need a hint?

A string is a sequence, so for character in product_code: walks it one character at a time, no indexing needed.

Show the solution
s06_practice02_sol_for_loops.py
# Problem-3 Task-1: a string is a sequence, so a for loop reads it one character at a time
product_code = "B4X2"
for character in product_code:
    print(character)

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, a running total, input(), f-strings.

Problem-1: Even Shelf Numbers.

Write a program that uses range() with a step of 2 to print the even shelf numbers from 0 to 10, one per line, and then prints total: followed by their sum.

Expected output
0
2
4
6
8
10
total: 30

range() stops before the end value

range() does not include its stop value. To reach 10, the stop must be one past it, so use range(0, 11, 2). Likewise range(1, 6) gives 1, 2, 3, 4, 5 (not 6).

Need a hint?

range(0, 11, 2) yields the even shelf numbers 0, 2, ... 10 because the third argument is the step and the stop value is excluded.

Show the solution
s06_practice03_sol_range.py
shelf_sum = 0
# Problem-1 Task-1: print even shelf numbers and their total
for shelf in range(0, 11, 2):
    print(shelf)
    shelf_sum += shelf
print("total:", shelf_sum)

View the full solution file on GitHub

Problem-2 (Write a Program): Bulk Price Table.

Write a program that asks the user for a unit price, then prints the cost for 1 to 5 units, with each line like 3 units cost 9.

Example run
Enter the unit price: 3
1 units cost 3
2 units cost 6
3 units cost 9
4 units cost 12
5 units cost 15
Need a hint?

Loop range(1, 6) and build each line with an f-string like f"{units} units cost {units * price}".

Show the solution
s06_practice03_sol_range.py
# Problem-2 Task-1: print the cost for 1 to 5 units
unit_price = int(input("Enter the unit price: "))
for units in range(1, 6):
    print(f"{units} units cost {unit_price * units}")

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, while loop, break, continue, pass, loop else, input().

Problem-1: First Bulk Order.

Write a program that, for the cart quantities 7, -4, 9, 12, 5, skips the invalid (negative) quantities, does nothing on the odd quantities, and at the first even quantity prints First bulk order: followed by that quantity and stops looking; if there is no even quantity, it prints No bulk order instead.

Expected output
First bulk order: 12
Need a hint?

continue skips to the next item, break exits early, pass does nothing, and a loop else runs only if no break fired.

Show the solution
s06_practice04_sol_break_continue.py
# Problem-1 Task-1: find and print the first even (bulk) quantity
cart_quantities = [7, -4, 9, 12, 5]
for quantity in cart_quantities:
    if quantity < 0:
        continue              # skip invalid quantities
    if quantity % 2 == 0:
        print("First bulk order:", quantity)
        break                 # stop at the first even quantity
    else:
        pass                  # odd quantity; nothing to do yet
else:
    print("No bulk order")

View the full solution file on GitHub

Problem-2 (Write a Program): Charge Each Order.

Write a program that keeps asking the user for an order amount until they type 0, skips any invalid (negative) amount, and for every other amount prints charged: followed by that amount.

Example run
Amount (0 to stop): 5
charged: 5
Amount (0 to stop): -2
Amount (0 to stop): 8
charged: 8
Amount (0 to stop): 0
Need a hint?

In a while True loop, test for 0 first to break, then for negative amounts to continue, before printing the charged amount.

Show the solution
s06_practice04_sol_break_continue.py
# Problem-2 Task-1: charge valid amounts until the user types 0
while True:
    amount = int(input("Amount (0 to stop): "))
    if amount == 0:
        break                 # stop on 0
    if amount < 0:
        continue              # skip invalid amounts
    print("charged:", amount)

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 for its keys, looping a dict with .items(), zip(), split(), input(), f-strings.

Problem-1: Number the Picking Steps.

Write a program that, for the picking steps scan badge, pick item, pack box, uses enumerate(start=1) to print each step numbered, like 1. scan badge.

Expected output
1. scan badge
2. pick item
3. pack box
Need a hint?

enumerate(steps, start=1) gives a (position, item) pair each pass, so unpack both in the for header.

Show the solution
s06_practice05_sol_enumerate_and_dict.py
# Problem-1 Task-1: number each picking step with enumerate
pick_steps = ["scan badge", "pick item", "pack box"]
for position, step in enumerate(pick_steps, start=1):
    print(f"{position}. {step}")

View the full solution file on GitHub

Problem-2: Order Totals.

Write a program that, for an order_totals dictionary of Order-1 set to 90, Order-2 set to 75, and Order-3 set to 60:

  • Task-1: loop the dictionary directly and print each order id (its keys), one per line.
  • Task-2: loop it with .items() and print each pair like Order-1: 90.
Expected output
Order-1
Order-2
Order-3
Order-1: 90
Order-2: 75
Order-3: 60
Need a hint?

Loop order_totals directly to print its keys (the order ids), then loop .items() to unpack order, amount together for the id: amount pairs.

Show the solution
s06_practice05_sol_enumerate_and_dict.py
order_totals = {"Order-1": 90, "Order-2": 75, "Order-3": 60}
# Problem-2 Task-1: loop the dict directly to get its keys (the order ids)
for order_id in order_totals:
    print(order_id)
# Problem-2 Task-2: print each order id and its total with .items()
for order_id, amount in order_totals.items():
    print(f"{order_id}: {amount}")

View the full solution file on GitHub

Problem-3 (Write a Program): Number the Packing Slip.

Write a program that asks the user for products separated by commas, then numbers them with enumerate(start=1), like 1. mouse (trim any spaces around each product).

Example run
Enter products separated by commas: mouse, keyboard, monitor
1. mouse
2. keyboard
3. monitor
Need a hint?

Split on , then call .strip() on each product to drop the spaces before numbering with enumerate(start=1).

Show the solution
s06_practice05_sol_enumerate_and_dict.py
# Problem-3 Task-1: number the user's comma-separated products
slip_text = input("Enter products separated by commas: ")
for line_no, product in enumerate(slip_text.split(","), start=1):
    print(f"{line_no}. {product.strip()}")

View the full solution file on GitHub

Problem-4: Pair Products with Prices (zip).

Write a program that, for cart_products holding "Mouse" and "Keyboard" and cart_prices holding 90 and 85, loops over both lists together with zip() and prints each pair like Mouse: 90.

Expected output
Mouse: 90
Keyboard: 85
Need a hint?

zip(cart_products, cart_prices) walks two equal-length lists in lockstep, yielding one pair per pass.

Show the solution
s06_practice05_sol_enumerate_and_dict.py
# Problem-4 Task-1: pair each product with its price using zip
cart_products = ["Mouse", "Keyboard"]
cart_prices = [90, 85]
for product, price in zip(cart_products, cart_prices):
    print(f"{product}: {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, looping a list, a list of lists, nested range(), break and continue inside nesting, an accumulator reset inside the outer loop, f-strings.

Problem-1: Gift-Wrap Menu.

Write a program that, for the products Mug, Frame and the wraps Plain, Floral, Holiday, uses a loop inside a loop to print every product-and-wrap option, one per line, like Mug in Plain wrap.

Expected output
Mug in Plain wrap
Mug in Floral wrap
Mug in Holiday wrap
Frame in Plain wrap
Frame in Floral wrap
Frame in Holiday wrap
Need a hint?

Put one for loop inside another; the inner wraps loop runs fully for each products value.

Show the solution
s06_practice06_sol_nested_loops.py
# Problem-1 Task-1: print every product-and-wrap option with nested loops
gift_products = ["Mug", "Frame"]
wraps = ["Plain", "Floral", "Holiday"]
for gift_product in gift_products:
    for wrap in wraps:
        print(f"{gift_product} in {wrap} wrap")

View the full solution file on GitHub

Problem-2: First Full Bin per Aisle.

Write a program that, for the aisles A1, A2 and bins 1 to 4, scans each aisle's bins in order and prints <aisle> bin <n> empty until it reaches bin 3 (the first full bin), where it prints <aisle> first full bin: 3 and uses break. Because break stops only the inner bin loop, the outer aisle loop still moves on to the next aisle.

Expected output
A1 bin 1 empty
A1 bin 2 empty
A1 first full bin: 3
A2 bin 1 empty
A2 bin 2 empty
A2 first full bin: 3
Need a hint?

break inside the inner bin loop stops only that loop at bin 3; the outer aisle loop still runs for every aisle.

Show the solution
s06_practice06_sol_nested_loops.py
# Problem-2 Task-1: break stops only the INNER bin loop; the outer aisle loop keeps going
for aisle in ["A1", "A2"]:
    for bin_no in range(1, 5):
        if bin_no == 3:
            print(f"{aisle} first full bin: {bin_no}")
            break
        print(f"{aisle} bin {bin_no} empty")

View the full solution file on GitHub

Problem-3: Bulk Pricing Grid.

Write a program that uses a nested range() loop to print a small pricing grid: for each unit count 1 to 3 and each pack size 1 to 2, print units x packs = total, like 1 x 1 = 1.

Expected output
1 x 1 = 1
1 x 2 = 2
2 x 1 = 2
2 x 2 = 4
3 x 1 = 3
3 x 2 = 6
Need a hint?

Nest a range(1, 3) packs loop inside a range(1, 4) units loop and print units * packs for the grid.

Show the solution
s06_practice06_sol_nested_loops.py
# Problem-3 Task-1: nested range x range builds a pricing grid
for units in range(1, 4):
    for packs in range(1, 3):
        print(f"{units} x {packs} = {units * packs}")

View the full solution file on GitHub

Problem-4: Skip the Reserved Bin.

Write a program that, for the aisles A1, A2 and the bins 1, 2, 3, prints every aisle-and-bin like A1 bin 1, but uses continue to skip bin 2 (reserved) on every aisle. The outer aisle loop still visits every aisle.

Expected output
A1 bin 1
A1 bin 3
A2 bin 1
A2 bin 3
Need a hint?

continue inside the inner bin loop skips only bin 2; the outer aisle loop still runs for every aisle.

Show the solution
s06_practice06_sol_nested_loops.py
# Problem-4 Task-1: continue skips only the reserved inner bin; the outer loop keeps going
for aisle in ["A1", "A2"]:
    for bin_no in range(1, 4):
        if bin_no == 2:
            continue
        print(f"{aisle} bin {bin_no}")

View the full solution file on GitHub

Problem-5: A List of Lists.

Define a variable day_orders as a list of lists with the values: [2, 3] and [1, 4, 2]. Write a program that prints the total for each day, then the grand total across all days.

Expected output
day total: 5
day total: 7
grand total: 12
Need a hint?

Loop the outer list to get each inner list, and reset day_total to 0 INSIDE that loop, before the inner loop adds the orders up.

Show the solution
s06_practice06_sol_nested_loops.py
# Problem-5 Task-1: an inner loop totals one day; the reset must sit INSIDE the outer loop
day_orders = [[2, 3], [1, 4, 2]]
grand_total = 0
for day in day_orders:
    day_total = 0          # reset for EVERY day: move this above the outer loop and the totals pile up
    for orders in day:
        day_total += orders
    print("day total:", day_total)
    grand_total += day_total
print("grand total:", grand_total)

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, split(), input().

Problem-1: Six Price Comprehensions.

Write a program that, for the cart prices 4, 7, 2, 9, 6:

  • Task-1: with a list comprehension, print a list of each price doubled.
  • Task-2: with a list comprehension and a filter, print a list of only the even prices.
  • Task-3: with a dict comprehension, print a dict that maps each price to its square.
  • Task-4: with a dict comprehension and a filter, print a dict that maps only the prices over 5 to their squares.
  • Task-5: for the ratings 5, 3, 5, 4, 3, use a set comprehension to print the sorted list of distinct ratings.
  • Task-6: with an if/else in a list comprehension, label each cart price "pricey" (5 or more) or "cheap".
Expected output
[8, 14, 4, 18, 12]
[4, 2, 6]
{4: 16, 7: 49, 2: 4, 9: 81, 6: 36}
{7: 49, 9: 81, 6: 36}
[3, 4, 5]
['cheap', 'pricey', 'cheap', 'pricey', 'pricey']
Need a hint?

[p * 2 for p in prices] builds a list; add if p % 2 == 0 to filter, {p: p * p for p in prices} for the dict (a trailing if filters it too), {r for r in ratings} for a set (drops duplicates - sort it), and ["pricey" if p >= 5 else "cheap" for p in prices] for the if/else choice.

Show the solution
s06_practice07_sol_comprehensions.py
cart_prices = [4, 7, 2, 9, 6]
# Problem-1 Task-1: print each price doubled
print([price * 2 for price in cart_prices])
# Problem-1 Task-2: print only the even prices
print([price for price in cart_prices if price % 2 == 0])
# Problem-1 Task-3: map each price to its square
print({price: price * price for price in cart_prices})
# Problem-1 Task-4: a dict comprehension can filter too: only prices over 5
print({price: price * price for price in cart_prices if price > 5})
# Problem-1 Task-5: a set comprehension drops duplicate ratings (sort it, a set is unordered)
ratings = [5, 3, 5, 4, 3]
print(sorted({rating for rating in ratings}))
# Problem-1 Task-6: an if/else inside the comprehension labels each price
print(["pricey" if price >= 5 else "cheap" for price in cart_prices])

View the full solution file on GitHub

Problem-2 (Write a Program): Square the Quantities.

Write a program that asks the user for quantities separated by spaces, then prints a list of their squares (use a comprehension to turn the text into ints).

Example run
Quantities separated by spaces: 2 3 4
[4, 9, 16]
Need a hint?

[int(x) for x in text.split()] converts the typed quantities to ints in one comprehension before squaring them in another.

Show the solution
s06_practice07_sol_comprehensions.py
# Problem-2 Task-1: print the squares of the user's quantities
qty_text = input("Quantities separated by spaces: ")
quantities = [int(x) for x in qty_text.split()]
print([qty * qty for qty in quantities])

View the full solution file on GitHub

Problem-3: Comprehension vs map.

Other code often uses map() with a lambda to transform a list. Use a comprehension instead.

Write a program that, for unit_counts holding 1, 2, 3, 4, uses a list comprehension to double each value and prints the resulting list.

Expected output
[2, 4, 6, 8]
Need a hint?

A list comprehension [x * 2 for x in unit_counts] replaces map(lambda x: x * 2, unit_counts) and reads more clearly.

Show the solution
s06_practice07_sol_comprehensions.py
# Problem-3 Task-1: double each value with a comprehension instead of map
unit_counts = [1, 2, 3, 4]
print([x * 2 for x in unit_counts])

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 workshop 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

Practice: Collections Next: Practice: Functions

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