Practice: else and finally

« Read the chapter

Q1. Use else

BeginnerCoding

Write code that converts '7' with int in try and, in else, prints the number plus 1.

Goal: Use else.

Q2. Always say done

BeginnerCoding

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

IntermediateCoding

Write f() that returns 'a' inside try and prints 'cleanup' in finally. Print f().

Goal: Understand return and finally.

Q4. Four blocks

IntermediateCoding

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

IntermediateCoding

Write code with a list log: append 'open', try appending 'use', finally appending 'close'. Print log.

Goal: Cleanup pattern.

Q6. Count successes

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
try:
    print('t')
    int('x')
except ValueError:
    print('e')
else:
    print('l')
finally:
    print('f')

Goal: Predict order.

Q8. Order without error

BeginnerOutput

What does this print?

Code
try:
    print('t')
except ValueError:
    print('e')
else:
    print('l')
finally:
    print('f')

Goal: Predict order.

Q9. Return and finally

IntermediateOutput

What does this print?

Code
def g():
    try:
        return 1
    finally:
        print('x')
print(g())

Goal: Return and finally.

Q10. Loop with finally

IntermediateOutput

What does this print?

Code
for i in range(2):
    try:
        print('try', i)
    finally:
        print('fin', i)

Goal: Finally in loops.

Q11. Finally overrides

AdvancedOutput

What does this print?

Code
def h():
    try:
        return 'a'
    finally:
        return 'b'
print(h())

Goal: Understand override.

Q12. Error in else

AdvancedOutput

What does this print?

Code
try:
    try:
        x = 1
    except ZeroDivisionError:
        print('inner')
    else:
        1 / 0
except ZeroDivisionError:
    print('outer')

Goal: Know else scope.

Q13. Fix the order

BeginnerDebugging

This has blocks in the wrong order. Fix it so it prints 5 then done.

Code
try:
    n = int('5')
finally:
    print('done')
else:
    print(n)

Goal: Block order.

Q14. Fix else without except

IntermediateDebugging

This is a syntax error. Fix it so it prints ok.

Code
try:
    x = 1
else:
    print('ok')

Goal: Valid try syntax.

Q15. Cleanup missing

IntermediateDebugging

The log should always get close, even on error. Fix it so it prints ['open', 'close'].

Code
log = ['open']
try:
    1 / 0
except ZeroDivisionError:
    pass
log.append('close')
print(log)

Goal: Use finally for cleanup.

Q16. Wrong block

IntermediateDebugging

The message should show only on success. Fix it so it prints nothing for bad input.

Code
try:
    int('z')
finally:
    print('success')

Goal: Choose else vs finally.

Q17. When does else run

BeginnerConceptual

When does the else block of a try statement run?

Goal: Know else.

Q18. Does finally always run

IntermediateConceptual

Does finally run if the try block contains a return? Explain.

Goal: Know finally.

Q19. Else versus end of try

IntermediateConceptual

Why is else better than putting code at the end of try?

Goal: Design try blocks.

Q20. Close a file

IntermediateApplication

Explain how finally helps when a program opens a file and an error occurs while using it.

Goal: Use cleanup.