Introduction.
It is commonly known that the worst form of torture is performing monotonous tasks ad nauseam. So I constructed this simple game I can give to my students when they misbehave.
Task.
The goal was to make a problem that could take in two numbers, and construct n
distinct multiplication problems where the user is asked to answer what x * y
is.
Challenge.
Where I struggled was with the part in cursive. How do I write a clear and readable code that produces distinct multiplication problems? I tried to do it with creating a sample of distinct numbers X
, and then choose y
such that y ≤ x
where x
is a member of X
. Unsure if this is the best idea.
The code and some comments
- I choose to do
import random
instead of importing the modules as it is a bit clearer where the modules comes from - As above, choose to include a short
___docstring___
more out of habit than necessity I guess.. - As mentioned above, do not really like my method for forcing the questions to be distinct.
- Tried to comply with pep8 for the long strings, looks a bit strange.
Here is the code
import random
QUESTIONS = 5
MIN_VAL = 2
MAX_VAL = 12
def arithmetic_game(val_1=MIN_VAL,
val_2=MAX_VAL,
num_of_problem=QUESTIONS):
""" Ask the user a series of arithmetic questions
and returns the number of correct answers.
Args: val_1 (int): Defines the range of multiplication
Args: val_2 (int): Defines the range of multiplication
Args: number_of_problems (int): Defines the number of questions
Return: correct_answers (int): number of correct math questions answered"""
correct_answers = 0
num_lst = random.sample(
range(min(val_1, val_2), max(val_2, val_2)+1),
num_of_problem)
for num_1 in num_lst:
num_2 = random.randint(2, num_1)
print('\nWhat is {:d} times {:d}?'
''.format(num_1, num_2))
answer = num_1*num_2
try:
if int(input()) == answer:
print('Yes, the answer is {:d}'
''.format(answer))
correct_answers += 1
else:
print('No, the correct answer was {:d}'
''.format(answer))
except NameError:
raise ValueError('I am sorry, you have'
'to write in a valid integer')
return correct_answers
if __name__ == "__main__":
correct_answers = arithmetic_game()
print('\nYou got {:d} out of {:d} answers correct'
''.format(correct_answers, QUESTIONS))