STR Coding Club logo STR Coding ClubLearn to code, together
Python and Practice

Python Try Except Exercises With Five Beginner Problems

Your program works perfectly until someone types "twelve" instead of 12, and then it crashes with a wall of red text.

A club member at a long table with a laptop showing a short Python program and a red error message, a paper test table with handwritten inputs beside the keyboard

Your program works perfectly until someone types "twelve" instead of 12, and then it crashes with a wall of red text. Most beginners know try and except exist but have never practised using them on purpose, so they either avoid them or wrap the whole program in one giant block. These Python try except exercises give you five short problems that build the habit properly, in the order I run them at club sessions.

What try and except actually do

A try block says "attempt this code". An except block says "if this particular error happens, do this instead of crashing". Python runs the try block line by line. The moment an error is raised, it jumps to the matching except block and skips whatever was left in the try.

The basic shape looks like this, written as four lines in your editor: try:, then age = int(input("Age: ")) indented underneath, then except ValueError:, then print("Please type a number") indented underneath.

Two more pieces appear in the exercises. An else block runs only when the try block finished with no error. A finally block runs no matter what, which is useful for clean up such as closing a file. You do not need either on day one, but you will meet both before exercise five.

If error messages still feel like noise, read our list of common Python mistakes new coders repeat first. Knowing the names ValueError, ZeroDivisionError, KeyError, IndexError and FileNotFoundError makes every exercise below easier.

Five Python try except exercises

Give yourself about 15 minutes per exercise. Write your own version before reading the hints, and run it at least three times with deliberately bad input.

Exercise 1: the safe age question

Ask the user for their age and print the age they will be in 10 years. If they type something that is not a whole number, print "That is not a number" instead of crashing.

What it teaches: catching one specific error. The int function raises ValueError when given text like "ten" or "12.5". Catch exactly that. Test it with 15, with "fifteen", with an empty input and with a space before the number. You will find that int quietly accepts " 15" because it strips spaces, which is a nice surprise.

Exercise 2: keep asking until it works

Extend exercise 1 so the program keeps asking until it gets a valid number, then prints the result once.

What it teaches: combining a loop with try and except. Use while True: with the try inside it. In the try, convert the input and then write break. In the except, print a friendly message, and the loop goes round again. A common mistake is putting break after the whole try and except block, which exits the loop even when the input was wrong.

Exercise 3: the pizza splitter

Ask how many slices there are and how many people are sharing, then print how many slices each person gets. Handle both text input and zero people with two separate messages.

What it teaches: more than one except block. Bad text raises ValueError. Dividing by zero raises ZeroDivisionError. Write one except for each, with its own message, so the user knows what to fix. With 8 slices and 3 people, the answer should be 2.67 when you round to two decimal places. With 8 slices and 0 people, you should see your zero message, not a crash.

Exercise 4: the score lookup

Create the dictionary scores = {"ana": 42, "ben": 37, "chi": 51}. Ask for a name and print that player's score. If the name is not in the dictionary, print "No score for that player".

What it teaches: KeyError, and an honest comparison with the alternative. Write it once with try and except KeyError. Then write it again using scores.get(name), which returns None instead of raising an error. Both are correct. Notice which one reads more clearly to you, because that judgement is the real skill here. Our Python dictionary practice exercises have more problems like this if you want extra reps.

Exercise 5: the notes file reader

Ask for a filename, open it, and print how many lines it has. If the file does not exist, print "File not found". Whatever happens, print "Done" at the end.

What it teaches: FileNotFoundError, else and finally together. Put the open call in the try. In except FileNotFoundError, print the message. In else, count the lines, because that should only happen when opening worked. In finally, print "Done". Test it with a real file of about 5 lines and with a made up name like notes_old.txt. Seeing "Done" in both runs is how you know finally does its job.

Why "wrap it all in try and except" is bad advice

Some beginner tutorials suggest putting your whole program inside one try with a bare except: underneath, so it "never crashes". I tell club members not to do this, and the reason is practical rather than about style.

A bare except catches every error, including the ones caused by your own typos. If you misspell a variable name, Python raises NameError, your catch all block swallows it, and the program prints "Something went wrong" forever. You lose the one message that would have told you exactly which line to fix. Even pressing Ctrl+C raises KeyboardInterrupt, which a bare except also catches, so a stuck loop becomes harder to quit.

The better habit has three parts:

  • Keep the try block small, ideally one to three lines around the risky call.
  • Name the exact error you expect, such as ValueError, never a bare except.
  • Let unexpected errors crash loudly while you are learning, because the crash is information.

Try and except are for problems you can predict and handle, like a user typing a word or a missing file. They are not a blanket over bugs you have not found yet.

How to check your answers without peeking

For each exercise, make a small test table on paper with three columns: what you typed, what you expected and what actually happened. Aim for at least four rows: one normal input, one wrong type, one edge case such as zero or an empty string, and one input you think might break it. If a row surprises you, that row is the lesson.

When you get stuck, resist the urge to search for a full solution. Print the type of the input, comment out the try so you can see the raw error, then put it back. Our guide on getting unstuck on a practice problem without peeking has more tactics that work well with these five.

Frequently asked questions

When should a beginner use try except in Python?

Use it when something outside your control can fail, such as user input, files or network requests. If the error comes from your own logic, fix the code instead of catching the error. A good test: can you write a helpful message for the user when it fails?

What is the difference between except and finally?

An except block runs only when a matching error happens in the try. A finally block runs every time, error or not. Use finally for clean up steps that must always happen, such as closing a file or printing a closing message.

Can I catch more than one error in one except?

Yes, by putting the error names in brackets, for example except (ValueError, ZeroDivisionError):. This is handy when both errors need the same response. If the user needs different advice for each, separate except blocks are clearer.

BN
Bartholomew Ng

Bartholomew taught maths for years before switching to teaching Python. He writes about the basics of the language and about teaching code without drowning learners in syntax.

More posts by Bartholomew

More in Python and Practice

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto