Я пытаюсь увеличить количество правильных ответов на 1 каждый раз, когда пользователи отвечают правильно. Однако при анализе в функции display_result() правильная функция отображает «0 правильно».
Я не смог заставить это работать, как бы я ни пытался шевелиться, поэтому любая помощь очень ценится.
code removed for academic integrity
Если пользователь правильно ответил на 1 из 3 вопросов, я ожидаю, что ответ будет «Вы правильно ответили на 1 вопрос из 3».
В настоящее время будет отображаться, что вы правильно ответили на 0 вопросов из 3"
В 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()
Есть ряд проблем:
correct = menu_option(option, correct)
, когда вместо этого вы должны накапливать правильные баллы, такие как correct +=
menu_option
вы никогда не назначаете count
, я полагаю, это должно быть count = check_solution(...)
return option
вместо index == 5
, потому что это добавит correct
.Ваш первый пункт неверен, так как check_solution()
обновляет счетчик: count = count + 1
@JohnnyMopp да, но я не вижу, чтобы это было определено снаружи, плюс это плохая практика.
Я не возвращал счет правильно, но, к сожалению, это для школьного задания, поэтому мне не разрешили изменить имена функций, переменные параметров или что-либо еще в функции main().
Наконец, код работает, как я и ожидал (требуется 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()
Потрясающий! Это работало с некоторыми незначительными изменениями, поскольку функция check_solution() вызывалась дважды для каждого ввода индекса. Но теперь работает :D.