4.2 Programming as a Step-Wise Strategy
91
return 1 without actually testing anything. In this way, we will be able to run the
program, while still having unfinished parts in there.
We have introduced N as a variable here to allow easy adjustment of “problem
size” (the total number of questions will be N*N). We know N must be 10, but that
requirement applies to the final version only. Thus, we are free to do our steps with
a smaller N, and that makes life much easier for us when assessing code behavior.
If you have not already done so, go through the code by hand to confirm that you
understand what happens, in what order.
When executed, the program simply prints:
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
1*1 =
1*1 = 1
Your score is now: 1
1*2 =
1*2 = 2
Your score is now: 2
2*1 =
2*1 = 2
Your score is now: 3
2*2 =
2*2 = 4
Your score is now: 4
Finished!
Your final score: 4
(max: 4)
From the printout, we see that the two functions seem to get the right arguments in
each call. We are thus ready for the next step, i.e., to implement the function bodies
of the two functions.
4.2.3 The 2nd Version of Our Code
After implementing the remaining parts of the code, we have a version
(times_tables_2.py) of our program that actually does the testing that was
asked for. The code reads
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
Précédent

- 112/350

Suivant