Practice: else and finally
Q1. Use else
Write code that converts '7' with int in try and, in else, prints the number plus 1.
Goal: Use else.
Q2. Always say done
Write code that tries int('x') with a ValueError handler printing 'bad', and a finally block printing 'done'.
Goal: Use finally.
Q3. Return with finally
Write f() that returns 'a' inside try and prints 'cleanup' in finally. Print f().
Goal: Understand return and finally.
Q4. Four blocks
Write code showing try, except, else and finally for int('5'): print t, e, l, f in the right blocks (t in try, e in except, l in else, f in finally). Only print blocks that run.
Goal: Order of blocks.
Q5. Resource log
Write code with a list log: append 'open', try appending 'use', finally appending 'close'. Print log.
Goal: Cleanup pattern.
Q6. Count successes
For items ['1', 'x', '3'] count conversions that succeeded using else, and print the count.
Goal: Use else in a loop.
Q7. Order with error
What does this print?
try:
print('t')
int('x')
except ValueError:
print('e')
else:
print('l')
finally:
print('f')Goal: Predict order.
Q8. Order without error
What does this print?
try:
print('t')
except ValueError:
print('e')
else:
print('l')
finally:
print('f')Goal: Predict order.
Q9. Return and finally
What does this print?
def g():
try:
return 1
finally:
print('x')
print(g())Goal: Return and finally.
Q10. Loop with finally
What does this print?
for i in range(2):
try:
print('try', i)
finally:
print('fin', i)Goal: Finally in loops.
Q11. Finally overrides
What does this print?
def h():
try:
return 'a'
finally:
return 'b'
print(h())Goal: Understand override.
Q12. Error in else
What does this print?
try:
try:
x = 1
except ZeroDivisionError:
print('inner')
else:
1 / 0
except ZeroDivisionError:
print('outer')Goal: Know else scope.
Q13. Fix the order
This has blocks in the wrong order. Fix it so it prints 5 then done.
try:
n = int('5')
finally:
print('done')
else:
print(n)Goal: Block order.
Q14. Fix else without except
This is a syntax error. Fix it so it prints ok.
try:
x = 1
else:
print('ok')Goal: Valid try syntax.
Q15. Cleanup missing
The log should always get close, even on error. Fix it so it prints ['open', 'close'].
log = ['open']
try:
1 / 0
except ZeroDivisionError:
pass
log.append('close')
print(log)Goal: Use finally for cleanup.
Q16. Wrong block
The message should show only on success. Fix it so it prints nothing for bad input.
try:
int('z')
finally:
print('success')Goal: Choose else vs finally.
Q17. When does else run
When does the else block of a try statement run?
Goal: Know else.
Q18. Does finally always run
Does finally run if the try block contains a return? Explain.
Goal: Know finally.
Q19. Else versus end of try
Why is else better than putting code at the end of try?
Goal: Design try blocks.
Q20. Close a file
Explain how finally helps when a program opens a file and an error occurs while using it.
Goal: Use cleanup.