FOR PYTHON: Write a function game() that teaches children how to add single-digi
ID: 3763311 • Letter: F
Question
FOR PYTHON: Write a function game() that teaches children how to add single-digit numbers. The function should take an integer n as a parameter and ask the child to answer n single-digit addition questions. The numbers should be chosen randomly from the range [0, 9] (that is including both 0 and 9). The user will enter the answer when prompted. Your function should print 'Correct' for correct answers and 'Incorrect' for incorrect answers. After n questions, the function should print the number of questions answered correctly. The function should also recover gracefully from non-integer values typed by the user. In those cases, the function should re-prompt the child to enter the answer without counting the invalid value either as correct or incorrect. The following shows several sample runs of the function:
Python 3.4.1 Shell File Fdit Sh Debug Options Windows Help >>game (3) 5+4= Enter ansver: nine Please enter your anser using digits (0-9) 5+4= Enter ansver: 9 Correct Enter anser: 3 Incorrect Enter ansver: 1 Correct Tou got 2 correct ansuers out of 3. >>>game (2) 0+8= Enter ansuer: eight Please enter your anser using digits (0-9) Enter ansuer: eight Please enter your anser using digits (0-9) 0+8= Enter anser: 8 Correct Enter ansver: 8 Correct Tou got 2 correct ansuers out of 2. Ln: 117 Col: 4Explanation / Answer
def game(n):
x = random.randrange (0,10)
y = random.randrange(0,10)
numbers = (x+y)
print (x, "+", y)
guess = eval(input("Enter your guess: "))
count = 0
total = 1
while total <= n:
x = random.randrange(0,10)
y = random.randrange(0,10)
numbers = x + y
print (x, "+", y)
guess = eval(input("Enter your guess: "))
total = total + 1
if guess == numbers:
count = count + 1
print("Correct.")
else:
print("Incorrect")
print("You got", count, "correct answers out of", total)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.