首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python 3:通过多个函数返回变量

Python 3:通过多个函数返回变量
EN

Stack Overflow用户
提问于 2019-04-10 06:56:50
回答 4查看 361关注 0票数 1

我遇到了一个基本的python问题,需要我做一个简单的加法测验。然而,我似乎不能返回我的count变量,该变量应该更新用户回答的正确问题的数量,这使得它停留在0。我尝试在每个函数中将变量count定义为参数,但仍然不起作用。假设用户回答了4个问题,并且答对了3个问题,那么它将显示为"You have answer 4 questions with 3 answer“,而不是显示"You have answer 4 questions with 0 answer”。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-04-10 07:08:08

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

代码语言:javascript
复制
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()
票数 2
EN

Stack Overflow用户

发布于 2019-04-10 07:03:41

正如注释所述,每次调用check_solution或menu_option时,都会将count初始化为0。

看起来你想使用count = count,这个变量被传递给你的函数。

只需快速编辑:

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

票数 1
EN

Stack Overflow用户

发布于 2019-04-10 07:06:54

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55602424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档