4.2 Programming as a Step-Wise Strategy
95
score = score + points(a, b, user_answer)
print(’Your score is now: {:d}’.format(score))
print(’\nFinished! \nYour final score: {:d}
(max: {:d})’\
.format(score, N*N))
Running this code, the order of the questions will be generated anew with each
execution (because of the randomization), but the dialogue may, for example, appear
like:
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
5 * 5 = 25
Correct!
Your score is now: 1
5 * 3 = 15
Correct!
Your score is now: 2
9 * 9 = 81
Correct!
Your score is now: 3
...
...

...
Finished!
Your final score: 95
(max: 100)
Great! Our code seems to run smoothly, so what can possibly go wrong now?
This will go wrong:
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
3 * 2 = six
Traceback (most recent call last):
...
...
< longer printout... author’s comment >
...
ValueError: invalid literal for int() with base 10: ’six’
If a user gives some unexpected input that the code is not prepared to handle,
things can go very wrong! In this case, we get an error message (referring to some
ValueError), since our program does not understand that “six” actually means the
number 6.
It would not be very professional to leave our program with this potential
problem, so it should be fixed, but how? The good news is that modern programming
languages, Python inclusive, do have the right tools to deal with such cases. For now,
we will leave our code as it is, but we hereby add yet another step to our program
development plan, and will solve the problem when we turn to exception handling
in Sect. 5.2. That will also bring us to the fourth version of our program, which also
Précédent

- 116/350

Suivant