94
4 Functions and the Writing of Code
i = 7 :
1*8 =
i = 8 :
1*9 =
i = 9 :
1*10 =
i = 10 :
2*1 =
i = 11 :
2*2 =
...
... < longer printout... author’s comment >
...
i = 97 :
10*8 =
i = 98 :
10*9 =
i = 99 :
10*10 =
Thus, from the 100 values of i, we can uniquely derive the two factors in all the
100 products (!), as the printout confirms. With the sequence of i values just shown,
however, we get the systematic ordering of the questions used in our 2nd version of
the program. So, to get the questions in random order, we need something more.
The second observation, is that the function shuffle (Sect. 2.4) from numpy
can be used to randomize the numbers 0 to 99, and thereby give us a randomized
ordering of the products.
Now, based on these two observations, we are ready to write down the 3rd
version of our program (times_tables_3.py), in which the functions ask_user
and points are unchanged compared to the 2nd version:
import numpy as np
def ask_user(a, b):
"""get answer from user: a*b = ?"""
question = ’{:d} * {:d} = ’.format(a, b)
answer = int(input(question))
return answer
def points(a, b, answer_given):
"""Check answer. Correct: 1 point, else 0"""
true_answer = a*b
if answer_given == true_answer:
print(’Correct!’)
return 1
else:
print(’Sorry! Correct answer was: {:d}’.format(true_answer))
return 0
print(’\n*** Welcome to the times tables test! ***\
\n
(To stop: ctrl-c)’)
N = 10
NN = N*N
score = 0
index = list(range(0, NN, 1))
np.random.shuffle(index)
# randomize order of integers in index
for i in range(0, NN, 1):
a = (index[i]//N) + 1
b = index[i]%N + 1
user_answer = ask_user(a, b)
Précédent

- 115/350

Suivant