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!.
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
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.
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
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.
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
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.
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
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
forloop. - 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.
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
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))
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.
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
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.
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
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.
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
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.
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
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.
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
# 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")
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.
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
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.
Need a hint?
enumerate(steps, start=1) gives a (position, item) pair each pass, so unpack both in the for header.
Show the solution
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 likeOrder-1: 90.
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
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}")
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).
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
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.
Need a hint?
zip(cart_products, cart_prices) walks two equal-length lists in lockstep, yielding one pair per pass.
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, 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.
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
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.
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
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.
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
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.
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
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.
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
# 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)
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
5to 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/elsein a list comprehension, label each cart price"pricey"(5 or more) or"cheap".
[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
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])
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).
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
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.
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
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.
Practice: Collections Next: Practice: Functions