#576 · Errors and exceptions · Beginner · 40 XP · about 7 min
Whatever happens in a room, the last person out turns off the lights. Python's finally block works the same way: its code runs when the try block finishes normally, when it raises an error, and even when it returns.
Write work_in(room, task):
room.lights_on = True, then call task() (a function that takes no arguments) and return what it returns.task() raises any exception, return 'failed: ' followed by the name of the exception's class, such as 'failed: ZeroDivisionError'. type(error).__name__ gives that name.room.lights_on must be False when work_in finishes.The Room class is provided.
room = Room() work_in(room, lambda: 6 * 7) # returns 42, and the lights are off again work_in(room, lambda: 1 / 0) # returns 'failed: ZeroDivisionError' work_in(room, lambda: room.lights_on) # returns True
The last example shows the lights were on while the task ran.
First solves only, ranked by stars and then time.