90
4 Functions and the Writing of Code
Based on these reflections, we choose to break up the programming task into
three steps:
• 1st version—has no dialogue with the user. It contains the double loop construction and two functions, ask_user and points. The function ask_user will
(in later versions) ask the user for an answer to a*b, while points (in later
versions) will check that answer, inform the user (correct or not), and give a
score (1 point if correct). To simplify, the function bodies of these two functions
will deliberately not be coded for this version of the program. Rather, we simply
insert a print command in each, essentially printing the arguments provided in
the call, to confirm that the function calls work as planned.
• 2nd version—asking and checking done systematically with predictable questions (first the 1 times table, then the 2 times table, etc.).
• 3rd version—asking and checking done with randomized questions. How to
implement this randomization, will be kept as an open question till we get there.
(We do reveal, however, that something “unforeseen” will be experienced with the
3rd version, which will motivate us also for a 4th version of the program.)
4.2.2 The 1st Version of Our Code
Our very first version of the code (times_tables_1.py) may be written like this:
def ask_user(a, b):
# preliminary
"""get answer from user: a*b = ?"""
print(’{:d}*{:d} = ’.format(a, b))
return a*b
def points(a, b, answer_given):
# preliminary
"""Check answer. Correct: 1 point, else 0"""
print(’{:d}*{:d} = {:d}’.format(a, b, a*b))
return 1
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))
In this implementation, the function ask_user will, by choice, not ask the user
about anything. It will simply return the correct answer. Regarding points, it will
Précédent

- 111/350

Suivant