每当用户回答正确时,我都会尝试将正确答案数增加1。但是,当解析为display_result()函数时,正确的函数将显示“ 0正确”
无论我如何尝试摆动它,我都无法使其正常工作,因此,非常感谢您的帮助。
code removed for academic integrity
如果用户正确回答了3个问题中的1个,我希望答案是“您正确回答了3个问题中的1个”。
当前,它将显示您已经正确回答了3个问题中的0个问题”
答案 0 :(得分:1)
在menu_option()
中,您永远不会修改count
,因此它保持为0。有两个简单的修复方法。更改为:
count = check_solution(user_solution, real_solution, count)
return count
或者只是
return check_solution(user_solution, real_solution, count)
我注意到的另一件事:在get_user_input()
中,您需要返回递归调用的结果:
else:
print("Invalid input, please try again")
return get_user_input()
答案 1 :(得分:0)
存在许多问题:
correct = menu_option(option, correct)
时应该累积correct +=
之类的正确分数menu_option
的{{1}}中,我想它应该是count
count = check_solution(...)
做return option
,因为那样会加到index == 5
。答案 2 :(得分:0)
最后,代码按预期运行(需要python3.6 +):
#!/usr/bin/env python3
import random
def get_user_input():
while True:
try:
index = int(input("Enter your choice: "))
if 0 < index < 6:
return index
except ValueError:
print("Invalid input, should be Integer.\n")
else:
print("Invalid input, please try again")
def get_user_solution(problem):
while True:
print("Enter your answer")
user_solution = input(f"{problem} = ")
try:
return float(user_solution)
except ValueError:
print("Invalid input, should be float\n")
def check_solution(user_solution, solution, count):
if user_solution == solution:
print("Correct.")
return count + 1
else:
print("Incorrect.")
return count
def menu_option(index, count):
first_num = random.randrange(1, 21)
second_num = random.randrange(1, 21)
if index == 1:
problem = f"{first_num} + {second_num}"
real_solution = first_num + second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 2:
problem = f"{first_num} - {second_num}"
real_solution = first_num - second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 3:
# blah blah blah, repeated code but removed for neatness
pass
if index == 5:
option = 5
return option
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct")
print("Your score is 0.0%")
else:
percentage = round(correct / total * 100, 2)
print(
f'You answered {total} questions with {correct} correct.\n'
f'Your score is {percentage}%'
)
def display_intro():
pass
def display_menu():
pass
def display_separator():
print('-'*20)
def main():
display_intro()
display_menu()
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
if __name__ == "__main__":
main()