April 2017
Beginner to intermediate
312 pages
7h 23m
English
The try...except...else block is especially useful when we want a certain block of code to be executed only when no exceptions are raised. In order to demonstrate this concept, let's rewrite the guessing game example using this block:
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.") elif input_value == rand_num: print("Your guess is correct! You win!") break else: print("Nope! The random value was %s" % rand_num)
The modified guessing game example that makes use of the try...except...else block is available for download along with this chapter as try_except_else.py. In this ...
Read now
Unlock full access