92
4 Functions and the Writing of Code
print(’\n*** Welcome to the times tables test! ***\
\n
(To stop: ctrl-c)’)
# Ask user for a*b, ... a, b are in [1, N]
N = 2
score = 0
for i in range(1, N+1, 1):
for j in range(1, N+1, 1):
user_answer = ask_user(i, j)
score = score + points(i, j, user_answer)
print(’Your score is now: {:d}’.format(score))
print(’\nFinished! \nYour final score: {:d}
(max: {:d})’\
.format(score, N*N))
Running the program, the dialogue could, for example, proceed like
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
1 * 1 = 1
Correct!
Your score is now: 1
1 * 2 = 2
Correct!
Your score is now: 2
2 * 1 = 3
Sorry! Correct answer was: 2
Your score is now: 2
2 * 2 = 4
Correct!
Your score is now: 3
Finished!
Your final score: 3
(max: 4)
We see that the behavior is as expected. Again, it is important that you read the code
and confirm that your understanding is in line with the output shown.
Testing for Equality with ==
In our code, we compare two integers in the if test
if user_answer == true_answer:
Testing for equality with == works fine for the integers we have here.
In general, however, such tests need to account for the inexact number
representation that we have on computers. More about this in Sect. 6.6.3.
Note that the new code implemented when updating from times_tables_1.py
to times_tables_2.py, included the function bodies in both functions ask_user
Précédent

- 113/350

Suivant