try...except...else...finally

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 = 0
valid_count = 0
while True:
# generate a random number between 0 and 9
rand_num = random.randrange(0,10)

# prompt the user for a number
value = input("Enter a number between 0 and 9: ")

if value == 'x':
print("Thanks for playing! Bye!")

try:
input_value = int(value)
except ValueError as error:
print("The value is invalid %s" % error)
else:
if input_value < 0 or input_value > 9:
print("Input invalid. Enter a number between 0 and 9.")
continue

valid_count += 1
if input_value == rand_num:
print("Your guess is correct! You win!")
break
else:
print("Nope! The random value was %s" % rand_num)
finally:
count += 1

print("You won the game in %d attempts "\
"and %d inputs were valid" % (count, valid_count))

The preceding code snippet is from the try_except_else_finally.py code sample (available for download along with this chapter). Try executing the code sample and playing the game. You will note the total number of attempts it took to win the game and the number of inputs that were valid:

    Enter a number between 0 and 9: g
The value is invalid invalid literal for int() with
base 10: 'g'

Enter a number between 0 and 9: 3
Your guess is correct! You win!
You won the game in 9 attempts and 8 inputs were valid

This demonstrates how the try-except-else-finally block works. Any code under the else keyword is executed when the critical code block (under the try keyword) is executed successfully, whereas the code block under the finally keyword is executed while exiting the try...except block (useful for cleaning up resources while exiting a code block).

Try providing invalid inputs while playing the game using the previous code example to understand the code block flow.