Practice: try and except
Q1. Safe conversion
Write code that tries int('12x') and prints 'bad number' if it fails.
Goal: Write try and except.
Q2. Default on failure
Write a function parse(text) that returns int(text) or -1 if it fails. Print parse('5') and parse('five').
Goal: Return defaults safely.
Q3. Missing key message
Given d = {'a': 1}, try d['z'] and print 'no such key' on KeyError.
Goal: Catch KeyError.
Q4. Sum valid numbers
For items = ['1', 'x', '3', 'y', '5'] add up the ones that convert and print the total.
Goal: Use try in loops.
Q5. Print the error
Try 10 / 0 and print the exception message.
Goal: Use the error object.
Q6. Input loop
Given the inputs, simulate with a list: for text in ['no', '8']: print 'retry' if it is not a number, otherwise print the number and stop.
Goal: Build an input loop.
Q7. Skipped line
What does this print?
try:
print('one')
int('x')
print('two')
except ValueError:
print('three')
print('four')Goal: Trace try flow.
Q8. No error
What does this print?
try:
print('go')
except ValueError:
print('error')
print('done')Goal: Know when except is skipped.
Q9. Wrong handler
What does this print?
try:
try:
int('x')
except KeyError:
print('key')
except ValueError:
print('value')Goal: Match exception types.
Q10. Function default
What does this print?
def f(t):
try:
return int(t)
except ValueError:
return 0
print(f('4') + f('a'))Goal: Follow return values.
Q11. Error name
What does this print?
try:
[][0]
except Exception as e:
print(type(e).__name__)Goal: Name exceptions.
Q12. Counting failures
What does this print?
bad = 0
for t in ['1', 'a', '2', 'b', 'c']:
try:
int(t)
except ValueError:
bad += 1
print(bad)Goal: Trace a loop with try.
Q13. Fix the bare handler
This handler hides every bug. Fix it to catch only the expected error and print 'bad'.
try:
int('q')
except:
passGoal: Avoid bare except.
Q14. Fix the indentation
This code has a syntax problem. Fix it so it prints ok.
try:
print(int('3'))
except ValueError:
print('bad')Goal: Write correct syntax.
Q15. Fix the wrong type
This does not catch the error. Fix it so it prints bad.
try:
int('z')
except KeyError:
print('bad')Goal: Use the right type.
Q16. Use the error later
The variable e is used after the except block and fails. Fix it to print the message.
try:
int('z')
except ValueError as e:
pass
print(e)Goal: Understand scope of e.
Q17. What if no error
Explain what Python does with the except block when the try block finishes without error.
Goal: Know the flow.
Q18. Why avoid bare except
Give two reasons why except: is a poor choice.
Goal: Avoid bad habits.
Q19. Small try block
Why should a try block be kept small?
Goal: Write focused try blocks.
Q20. Age form
A form asks for age. Describe how try and except can keep it from crashing when the user types 'abc'.
Goal: Validate input.