I have been given a basic python problem that requires me to make a simple addition quiz. However, I cannot seem to return my count variable which is supposed to update the number of correct questions the user has answered, which makes it stuck at 0. I have tried defining the variable count in every function containing it as an argument but still does not work. Say if the user were to answer 4 questions and got 3 correct, it would display it as "You have answered 4 questions with 3 correct", but instead it displays "You have answered 4 questions with 0 correct".
Every time your check_solution
and menu_option
functions get called, you initialize count = 0
. This means every time the user requests another question, count
gets reset to 0, twice. You're going to want to remove those count = 0
calls, and you also want to capture your updates to count within menu_option
. Your final program should look something like this:
import random
def get_user_input():
count = 0
user_input = int(input("Enter 1 to play or press 5 to exit: "))
while user_input > 5 or user_input <= 0:
user_input = int(input("Invalid menu option. Try again: "))
menu_option(user_input, count)
if user_input == "5":
print("Exit!")
return user_input
def get_user_solution(problem):
answer = int(input(problem))
return answer
def check_solution(user_solution, solution, count):
curr_count = count
if user_solution == solution:
curr_count += 1
print("Correct.")
else:
print("Incorrect.")
print(curr_count)
return curr_count
def menu_option(index, count):
if index == 1:
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)
randsum = num1 + num2
problem = str(num1) + " " + "+" + " " + str(num2) + " " + "=" + " "
user_answer = get_user_solution(problem)
count = check_solution(user_answer, randsum, count) # count returned by check_solution is now being captured by count, which will update your count variable to the correct value
return count
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct.")
print("Your score is 0%. Thank you.")
else:
score = round((correct / total) * 100, 2)
print("You answered", total, "questions with", correct, "correct.")
print("Your score is", str(score) + "%.")
def main():
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exiting.")
display_result(total, correct)
main()