python3:通过多个函数返回变量

2024-04-26 11:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个基本的python问题,需要我做一个简单的加法测试。但是,我似乎无法返回count变量,该变量用于更新用户回答的正确问题的数量,这使得它停留在0。我尝试过在每个包含变量count的函数中将其定义为参数,但仍然不起作用。假设用户回答了4个问题,得到了3个正确答案,它将显示为“Youhave answere 4 questions with 3 correct”,但它显示的是“You have responsed 4 questions with 0 correct”。在


Tags: 函数答案用户you参数数量定义have
3条回答

您需要从check_solution(user_answer, randsum, count)捕获返回值并返回该计数

每次调用check_solutionmenu_option函数时,都要初始化count = 0。这意味着每当用户请求另一个问题时,count会被重置为0,两次。您将要删除这些count = 0调用,还希望捕获更新以在menu_option内计数。你的最终计划应该是这样的:

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()

正如注释所述,每次调用check_解决方案或menu_选项时,都会将count初始化为0。在

看起来您想使用count = count传递给函数的变量。在

只需快速编辑:

你实际上不需要返回count。在Python中,变量是通过引用传递的,因此只要将计数传递给函数,就会更新计数。在

相关问题 更多 >