Python debugging exercises
Writing Python is taught everywhere. Reading Python that almost works, and finding the one line that makes it wrong, is mostly learned the hard way. These exercises are that skill on its own: each one is a short function with a single bug, a description of what goes wrong, and tests that pass only when you have fixed it.
They start with the bugs every beginner meets — an index one past the end, a method that returns None, a string that looks like a number — and move on to shared references, scope and the gotchas that still catch experienced developers. Everything runs in your browser through Pyodide, so there is nothing to install.
Practise by topic
How to debug a Python function
- Reproduce it. Run the failing input and read the whole traceback, bottom line first: the exception type and message usually name the problem exactly.
- Find the line, then the value. The last line of your own code in the traceback is where it broke; print the variables used on that line just before it runs.
- Compare with what you expected. Work out by hand what each value should be. The first variable that differs is closer to the bug than the line that crashed.
- Fix the cause, not the symptom. Wrapping a line in try/except hides the error; ask why the value was wrong in the first place.
- Rerun every test, not just the failing one. A fix that breaks a different case was a guess.
Python debugging tools to practise with
print()
print(f"{i=} {total=}")The fastest check. The = inside an f-string prints the name and the value, so you can see each variable change as the loop runs.
breakpoint()
breakpoint()Put it on the line before the bug. Python stops there and opens pdb, so you can look at every variable at that moment.
pdb commands
p total n s c qInside pdb: p prints a value, n runs the next line, s steps into a function call, c continues to the next breakpoint, q quits.
Read the traceback
IndexError: list index out of rangeStart at the bottom line: the exception type and message. The last line from your own file above it is where it broke.
In the exercises, each check shows what your function returned and any traceback. To watch values change line by line, paste the code into the step-through visualizer. Use breakpoint() and pdb on your own machine.
The exercises
Easy
- Sum from 1 to n leaves out nOff-by-one
- Price label crashes on a numberType
- Checkout works without a valid paymentLogic
- Settings lookup crashes on a missing keyNull and undefined
- Average of 1 and 2 comes out as 1Type
- Word count says 3 for "hello world"Logic
- Shout function returns lowercase textMutation and copying
- Last even number crashes when there is noneScope and closure
- Retry loop never stops on successInfinite loops
- Middle item lookup crashes with TypeErrorType
- Last letter crashes with IndexErrorOff-by-one
- Sorted name list comes back as NoneMutation and copying
- Adding a tag makes the whole list disappearMutation and copying
- AI Attempt: The palindrome checkerType
- Countdown never reaches zeroOff-by-one
- Capitalizing a name crashes with TypeErrorType
- AI Attempt: FizzBuzz never says FizzBuzzLogic
- Age next year crashes on form inputType
- Vowel counter skips capital lettersLogic
- Shopping total crashes at the end of the listOff-by-one
- Price parser rejects prices with centsType
- Letter counter crashes on the first letterNull and undefined
- Prime checker thinks 1 is primeLogic
- Cart total adds up positions, not pricesLogic
- Removing duplicate tracks changes the orderMutation and copying
- Quiz marks "Paris " wrong because of a spaceLogic
- Leaderboard shows the three worst playersLogic
- Greeting prints but the page shows nothingMutation and copying
- Weekend check says Monday is the weekendLogic
- Exam percentage always comes out as 0Type
- Total only counts the first itemLogic
- Search gives up after checking one itemLogic
- Squaring 3 gives 1Mutation and copying
- Average of 4 and 6 comes out as 7Logic
- Name splitter crashes on a middle nameMutation and copying
- Setting "False" still turns the switch onType
- Word search misses a match at the startLogic
- Receipt is empty after the cart is clearedMutation and copying
- 100 °C converts to 237.6 °FLogic
- Timer shows 2:5 instead of 2:05Mutation and copying
- 3 tickets at 20 gives "333…" instead of 60Type
- Counting digits crashes on a numberType
- Comparing each day with the next crashes at the endOff-by-one
- Preview cuts off one letter too soonOff-by-one
- try/except still crashes on 0 / 0Mutation and copying
- Top scorer is picked alphabeticallyLogic
- Contact list puts capital names firstLogic
- Reversing words also reverses the lettersLogic
- Adding two items puts a list inside the listMutation and copying
- Shopping list numbering starts at 0Off-by-one
- Queue serves the last person firstLogic
- Tags after a comma start with a spaceMutation and copying
- Shipping cost is blank for small ordersNull and undefined
- PIN builder crashes on a list of digitsType
- Reading keeps going after the stop markerLogic
- Blank name gives an empty greetingNull and undefined
- Swapping two values copies one over the otherLogic
- Ranking sorts students by name, not scoreLogic
- Prices show $2.5 instead of $2.50Mutation and copying
- Even-number total adds up the odd onesLogic
- Tip calculator crashes with NameErrorScope and closure
- Purging inactive sessions raises dictionary changed sizeLogic
- Boolean argument passes integer check and increments to twoType
- Comparing high user IDs with is keyword returns falseLogic
- Joining path with leading slash discards base directoryLogic
- Removing even numbers while looping skips adjacent itemsLogic
- Matching digits inside string returns None with re matchLogic
- Summarizing stream twice causes generator to return zero sumLogic
- Floor division on negative number rounds away from zeroLogic
- Checking length of filter object raises TypeErrorType
- Calculating bonus raises UnboundLocalError when condition is falseScope and closure
- Stripping file suffix strips filename characters as a setLogic
- Counting words using space delimiter overcounts on multiple spacesLogic
- Removing duplicate items with set scrambles original orderLogic
- Integer division for pagination leaves remainder items outLogic
- All function on empty user list evaluates to trueLogic
- Finding max on empty score list raises ValueErrorLogic
- Itertools groupby on unsorted list splits identical keysLogic
- Round function rounds 2.5 down to 2 instead of up to 3Logic
- Single element tuple without comma evaluates to integerType
- Looking up integer user ID in loaded JSON raises KeyErrorType
- Passing list of types to isinstance raises TypeErrorType
- Sorting list with sort method returns None instead of listType
- Floating point subtraction in price calculator leaves precision artifactLogic
- Counter subtraction retains zero count keys in dictionaryLogic
- Subclass check with type identity fails for inherited classesType
- Timedelta total seconds called as attribute raises AttributeErrorType
- Stripping protocol prefix strips domain characters as setLogic
- Set difference operator direction inverts unmatched itemsLogic
- Zipping uneven lists silently drops unmatched trailing itemsLogic
- Negative banker rounding rounds midpoint toward even integerLogic
- Appending sublist of roles nests array instead of extendingType
- Popping from empty stack raises IndexError without checkLogic
- Four digit year string raises ValueError with lowercase y formatType
- Sum function with string elements raises TypeErrorType
- Finding minimum on empty transaction list raises ValueErrorLogic
- String split on newline retains empty trailing element unlike splitlinesLogic
- Floating point fee calculation leaves precision artifactLogic
- Subclass check with isinstance accepts instances instead of classType
- Single quoted dictionary string raises JSONDecodeErrorType
- Dictionary fromkeys shares default mutable list across all keysLogic
- Index method on list raises ValueError when item is missingLogic
- Boolean evaluation on custom empty container treats object as falseLogic
- Reversing list in place with reverse method returns NoneType
- Leaderboard crashes before anyone has playedNull and undefined
- Longest-word finder returns the shortestLogic
- Doubling the prices doubles the list insteadLogic
- Reversed text shows <reversed object at 0x…>Type
- Pass counter counts everyoneLogic
- Word filter finds "cat" inside "cats"Logic
- Staircase pattern starts with an empty stepOff-by-one
- Queue position crashes for someone not in lineNull and undefined
- Ingredient list ends with a stray commaOff-by-one
- File type check reads .tar.gz as tarLogic
- CSV reader splits a line into lettersType
- A@x.com and a@x.com count as two peopleLogic
- Student greeting can't find the nameScope and closure
- New product page crashes on average ratingNull and undefined
- Every order is labelled smallLogic
- Welcome message shows {name} instead of the nameLogic
- Playlist reverser crashes with IndexErrorOff-by-one
- Phone number cleaner changes nothingLogic
- Number check says 5 is not a numberType
- Checkout crashes when adding taxNull and undefined
- Class report crashes after adding up the scoresType
- Star rating always rounds downType
- Newsletter sign-up ignores every yesLogic
- Sign-up turns away people who are exactly 18Off-by-one
- Quiz score of 7.5 rejected as invalidType
- Basket total equals the last item's priceLogic
- Long-word counter returns 0 for elephantLogic
- Initials come out as the second lettersOff-by-one
- Restocking sets the count to 1Logic
- Five-star check won't even startMutation and copying
- Lucky number check never finds 5Type
- Member discount never appliesType
- Tag list ends with an empty tagMutation and copying
Medium
- Countdown never stopsInfinite loops
- Factorial crashes with RecursionErrorMutation and copying
- Full name crashes when there is no middle nameNull and undefined
- Last 3 letters comes back with 4Off-by-one
- A score of 95 gets a DLogic
- Adding up digits never finishesInfinite loops
- Leap year check says 2000 was not a leap yearLogic
- Merging settings changes the defaultsMutation and copying
- 50% off 200 comes to 150Logic
- Adding to total crashes with UnboundLocalErrorScope and closure
- Removing double spaces freezesInfinite loops
- Collatz steps freeze on odd numbersInfinite loops
- Highest score picks "9" over "10"Type
- Comparing form values to a number crashesType
- Setting retries to 0 gives 3 retriesNull and undefined
- Total score crashes on a player with no scoreNull and undefined
- Range count skips the lowest valueOff-by-one
- "All positive" check accepts a negative numberLogic
- Biggest gap between numbers comes out as -1Logic
- Adding up a dict's values crashesMutation and copying
- Second list still has the first call's itemScope and closure
- AI Attempt: The Two Sum TrapLogic
- Highest temperature reads 0 on a cold dayLogic
- Spam filter removes only the first "spam"Logic
- Login says a registered user doesn't existLogic
- 2.5 rounds down to 2 instead of up to 3Mutation and copying
- AI Attempt: The runner-up finderLogic
- Adding up "4,5,6" crashesType
- Admin check rejects the adminLogic
- AI Attempt: The anagram checkerLogic
- Booking one seat books the whole columnMutation and copying
- Age is a year too high before the birthdayLogic
- Role check lets "adm" throughType
- Pages needed comes back as 2.5Type
- AI Attempt: Fibonacci starts one step aheadOff-by-one
- Label maker says str is not callableScope and closure
- Duplicate finder reports each duplicate twiceLogic
- Removing https:// eats the start of shop.comMutation and copying
- Swapping rows and columns drops a columnOff-by-one
- Click counter crashes on the first clickScope and closure
- AI Attempt: The bracket checkerLogic
- Pair finder returns the last pair, not the firstLogic
- Counting map pins crashes on [x, y] pointsType
- Class variable list leaks items across multiple user cartsScope and closure
- Multiplying row list in matrix creates identical row referencesScope and closure
- Shallow dictionary copy mutates original nested port in placeLogic
- Mutable default context dictionary accumulates keys across callsScope and closure
- AI Attempt: The missing number finderOff-by-one
- Update check thinks 10.0 is older than 9.4Type
- Leave calculator counts one day shortOff-by-one
- Price in cents comes out one cent shortType
- Headline formatter writes Don'TMutation and copying
- New team member vanishes from a new teamMutation and copying
- AI Attempt: Caesar cipher runs off the alphabetLogic
- Payment check says 0.1 + 0.2 isn't 0.3Type
- Number check rejects negative numbersType
- Empty basket reports one itemLogic
- Empty test run reported as all passingLogic
- Removing .txt turns test.txt into esLogic
- AI Attempt: Merging two sorted listsLogic
- Removing sold-out items crashesLogic
- AI Attempt: Maximum subarray sumLogic
- Scoreboard drops the player who hasn't playedLogic
- Fastest lap crashes when a driver doesn't finishType
- Express-only shipping comes out as single lettersType
- AI Attempt: First non-repeating characterLogic
- AI Attempt: Rotating an array by kOff-by-one
- AI Attempt: Longest common prefixOff-by-one
- AI Attempt: Reversing a negative number crashesType
Hard
- Binary search can't find the last itemOff-by-one
- Two shoppers end up with the same basketScope and closure
- Changing the copy also changes the originalMutation and copying
- Removing even numbers leaves one behindMutation and copying
- All multipliers use the last numberScope and closure
- New basket already has the first basket's itemScope and closure
- Counting pairs freezes when a pass finds noneInfinite loops
- Lookup says KeyError: 1, but 1 is right thereType
- A reading of 0 degrees counts as missingNull and undefined
- First match crashes with StopIterationNull and undefined
- Splitting into groups loses the last groupOff-by-one
- Best window of 2 misses the last pairOff-by-one
- Divide-by-zero check comes too lateLogic
- Editing a copied grid changes the originalMutation and copying
- Three multipliers all multiply by 2Scope and closure
What you will practise
Questions
Do I need to install Python?
No. The code runs in your browser with Pyodide, a full Python interpreter compiled to WebAssembly. Nothing is sent to a server.
I am a beginner. Where should I start?
With the easy ones below, in any order. Each takes a few minutes, and the hints get warmer one at a time if you are stuck.
Is there a certificate?
Yes, free. Fixing 25 easy Python bugs while signed in earns Python Debugging · Level 1, with a verification link for your LinkedIn profile.