This page contains Python practice problems with worked answers, each focused on one concept so you can see exactly what you've mastered. They're arranged so you attempt each problem before reading its reasoning, which is the part that makes practice effective.
def broadcast_seconds(minutes, seconds):
if minutes < 0 or not 0 <= seconds < 60:
raise ValueError("Invalid duration")
return minutes * 60 + seconds
print(broadcast_seconds(4, 25)) # 265The four problems cover converting durations, counting frequencies, totalling a validated CSV file and keeping object state independent, set at a community radio station. After them, you'll find how to practise so the skill transfers to new problems: focusing on one idea, studying worked reasoning, delaying solutions and applying the same idea elsewhere. For multi-step problems, continue to coding challenges.
Focused practice
A focused problem isolates one concept, so that when you get it wrong you know what to review. The four problems here each target a different skill:
| Problem | Concept practised | Review lesson |
|---|---|---|
| 1. Durations to seconds | arithmetic, validation, functions | numbers, functions |
| 2. Most played tracks | dictionaries and counting | dictionaries |
| 3. Validated CSV totals | files, conversion, error handling | CSV handling |
| 4. Independent playlists | objects and mutable state | classes and objects |
An oversized task, such as "build a radio scheduling app", mixes so many skills that a failure tells you little. Small problems also give quick feedback, which keeps practice sessions productive. Do one or two focused problems a day rather than a long session once a week; spacing practice out helps you remember it.
Worked reasoning
For each problem, the reasoning that connects the question to the code matters more than the final lines. Here is problem 1 worked through:
- Restate: convert minutes and seconds into total seconds, rejecting impossible values.
- Rules: minutes can't be negative; seconds must be 0 to 59, since 60 seconds would be another minute.
- Method: total = minutes × 60 + seconds.
- Check by hand: 4 min 25 s → 240 + 25 = 265.
- Edge cases: 0 min 0 s → 0; 0 min 59 s → 59; 1 min 60 s → error.
for args in [(0, 0), (0, 59), (1, 60)]:
try:
print(args, broadcast_seconds(*args))
except ValueError as error:
print(args, "->", error)Code shown without reasoning encourages memorising lines rather than understanding choices. When you write your own solutions, write steps like these as comments first, then fill in the code beneath each one.
Delayed solutions
Attempt each problem before looking at the answer, and write down a prediction or plan, even if you're unsure. Struggling briefly to recall and apply an idea, called retrieval practice, is what strengthens memory; reading a solution straight away feels productive but leaves little behind.
A simple routine:
- Read the problem and write your plan in comments.
- Write the code and run your own test cases.
- If a test fails, explain why in one sentence before changing anything.
- Only then compare with the worked answer, noting any difference in approach.
If you're stuck for more than about fifteen minutes, read just the first step of the worked reasoning, then try again. Hints in the course exercises work the same way: open the hint before the solution.
Transfer
After solving a problem, apply the same idea to a different situation. Problem 1's duration logic transfers to rehearsal schedules, cooking timers and video timestamps:
def rehearsal_minutes(hours, minutes):
if hours < 0 or not 0 <= minutes < 60:
raise ValueError("Invalid rehearsal length")
return hours * 60 + minutesTransfer is the real test of understanding. Renaming variables isn't transfer; noticing that the same rule ("units must be in range, then combine with a multiplier") applies, and checking whether its assumptions still hold, is. For example, a timestamp 1:05:30 adds an hours unit, so the function needs a third parameter and range check.
When a transferred version fails, compare it with the original: the difference usually reveals an assumption you hadn't noticed.
Independent practice and a worked check
Task: solve duration conversion, frequency counting, validated CSV totals and independent object state problems with written reasoning. Try these variations without looking back:
# 1. Extend broadcast_seconds to accept hours, minutes and seconds.
# 2. Return the single least played track, ties broken alphabetically.
# 3. Total CSV minutes per show type, where a 'type' column is added.
# 4. Give Playlist a remove(track) method that ignores missing tracks.
def broadcast_seconds(hours, minutes, seconds):
if hours < 0 or not 0 <= minutes < 60 or not 0 <= seconds < 60:
raise ValueError("Invalid duration")
return hours * 3600 + minutes * 60 + seconds
print(broadcast_seconds(1, 5, 30)) # 3930The first variation is solved as a model; write reasoning comments for the other three before coding them. For the worked check, you attempt a problem before reading its solution to expose your current reasoning and gaps.
Reference and next practice
Work through the interactive Python exercises, filtering by chapter and difficulty, and the Python quiz. Continue with exercises by difficulty and beginner projects.
Python Practice Problems Summary
- Focused practice: A focused problem isolates one concept so the learner can see what changed.
- Worked reasoning: A worked answer explains the choices connecting the question to the code.
- Delayed solutions: Attempt the task and record a prediction before comparing a worked solution.
- Transfer: Apply the same idea to another domain after solving the first version.
Python Practice Problems Examples
Each example shows the code, the output it produces and what each part does.
Python Practice Problems in a small program
Problem 1, with its answer: convert a broadcast length to seconds.
def broadcast_seconds(minutes, seconds):
if minutes < 0 or not 0 <= seconds < 60:
raise ValueError("Invalid duration")
return minutes * 60 + seconds
print(broadcast_seconds(4, 25))265Line-by-line explanation
- Lines 2 to 3Invalid values are rejected before any calculation.
- Line 4Minutes are converted to seconds and added.
- Line 64 × 60 + 25 = 265.
Problem 2: the most played tracks
Given a play log, return the two most played tracks, with ties broken alphabetically.
log = ["Blue Hour", "Tides", "Blue Hour", "Northbound", "Tides", "Blue Hour", "Aria", "Aria"]
counts = {}
for track in log:
counts[track] = counts.get(track, 0) + 1
top_two = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))[:2]
print(counts)
print(top_two){'Blue Hour': 3, 'Tides': 2, 'Northbound': 1, 'Aria': 2}
[('Blue Hour', 3), ('Aria', 2)]Line-by-line explanation
- Lines 4 to 5Count each track with a dictionary.
- Line 7Sort by count descending (negated) then by name, so "Aria" beats "Tides" when both have two plays.
Problem 3: total a CSV file and report bad rows
import csv, io
text = "show,minutes\nMorning Mix,45\nNews,15\nJazz Hour,sixty\nTalkback,30\n"
total, bad = 0, []
for line_no, row in enumerate(csv.DictReader(io.StringIO(text)), start=2):
try:
total += int(row["minutes"])
except ValueError:
bad.append(f"line {line_no}: {row['minutes']!r}")
print("Total minutes:", total)
print("Rejected:", bad)Total minutes: 90
Rejected: ["line 4: 'sixty'"]Line-by-line explanation
- Line 5Line numbers start at 2 because line 1 is the header.
- Lines 6 to 9Each conversion failure is recorded with its line instead of stopping the whole import.
Problem 4: keep playlists independent
class Playlist:
def __init__(self, name, tracks=None):
self.name = name
self.tracks = list(tracks) if tracks is not None else []
def add(self, track):
self.tracks.append(track)
base = ["Station ident"]
morning = Playlist("Morning", base)
evening = Playlist("Evening", base)
morning.add("Wake-up song")
print(morning.tracks)
print(evening.tracks)
print(base)['Station ident', 'Wake-up song']
['Station ident']
['Station ident']Line-by-line explanation
- Line 4
list(tracks)copies the starting tracks, so each playlist owns its own list. Without the copy, both playlists andbasewould share one list. - Lines 12 to 15Adding to the morning playlist leaves the evening playlist and the original list unchanged.
Common Python Practice Problems Mistakes
Reading the solution before attempting the problem
Read problem -> read solution -> "that makes sense" -> next problemRead problem -> write a plan -> code and test -> explain any failure -> compare with the solutionRecognising a correct answer is much easier than producing one; only the second routine builds the skill.
Sharing a mutable default between objects
class Playlist:
def __init__(self, name, tracks=[]):
self.tracks = tracks # every playlist shares one listclass Playlist:
def __init__(self, name, tracks=None):
self.tracks = list(tracks) if tracks is not None else []Python Practice Problems in Real Projects
Practice that transfers to real work
The problems on this page mirror everyday programming tasks: converting units and validating input, summarising logs, importing spreadsheet exports without losing bad rows silently, and keeping objects independent. Developers solve versions of them constantly, usually inside larger programs.
Practising with focus, worked reasoning, delayed solutions and transfer is how professionals learn new libraries and languages too: read a small example, predict, try a variation, then apply it to their own problem.
Python Practice Problems FAQ
Where can I practise Python for free?
This course's Python exercises and quiz are free and run in the browser, with hints and explanations. The practice problems on this page, small projects of your own and sites such as Exercism also offer free practice.
How many Python problems should I solve per day?
Consistency matters more than volume: one to three focused problems a day, attempted properly before checking answers, builds more skill than a long weekly session. Increase difficulty when you solve problems comfortably.
What should I do when I'm stuck on a Python problem?
Re-read the problem, test a tiny example by hand, add print() calls to see what your code is doing, and explain the issue in one sentence. If still stuck after about fifteen minutes, read only the first hint or reasoning step, then try again.
Are practice problems enough to learn Python?
They build fluency with concepts, but you also need projects, which combine many skills and require design decisions. Alternate between focused problems and a small project that uses what you've practised.
How do I know my solution is correct?
Test it with ordinary cases, boundary cases (empty, zero, maximum) and cases that might break it, and compare results with values worked out by hand. Then compare your approach with the worked answer to learn alternatives.
Python Practice Problems Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Why attempt a problem before reading its solution?
Which review concern is valid for Python practice problems?
Python Practice Problems Quiz
2 questions to check what you learned.
Why attempt a problem before reading its solution?
- To guarantee a perfect first answer
- To expose your current reasoning and gaps
- Python ignores the distinction
Which statement correctly describes delayed solutions?
- Attempt the task and record a prediction before comparing a worked solution.
- Only the example output matters, not the rule
- Every operation has the same behavior