April 2017
Beginner to intermediate
312 pages
7h 23m
English
As the name suggests, the finally block is used to execute a block of code on leaving the try block. This block of code is executed even after an exception is raised. This is useful in scenarios where we need to clean up resources and free up memory before moving on to the next stage.
Let's demonstrate the function of the finally block using our guessing game. To understand how the finally keyword works, let's make use of a counter variable named count that is incremented in the finally block, and another counter variable named valid_count that is incremented in the else block. We have the following code:
count = 0valid_count = 0while True: # generate a random number between 0 and 9 rand_num = random.randrange(0,10) ...
Read now
Unlock full access