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

问题描述 投票:0回答:5

我得到了一个基本的python问题,需要我做一个简单的加法测验。但是,我似乎无法返回我的计数变量,它应该更新用户已经回答的正确问题的数量,这使得它停留在0.我已经尝试在包含它作为参数的每个函数中定义变量计数但仍然不行。如果用户要回答4个问题并且得到3个正确,则会将其显示为“您已回答4个问题并且3个正确”,而是显示“您已回答4个问题且0个正确”。

python function loops return
5个回答
1
投票

每当你的check_solutionmenu_optionfunctions被调用时,你就会初始化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()


1
投票

你需要从check_solution(user_answer, randsum, count)获得回报并返回该数量


1
投票

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

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

只需快速编辑:

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


0
投票

您可以选择在所有函数之前将count初始化为0,从而创建全局变量。然后你不需要在任何函数上声明它,也不需要将它作为参数传递。


0
投票

这是逻辑中的几个错误的顶点。

  • 您将count作为输入提供,并立即覆盖它。 我会改为说def menu_option(index, count=0):。如果没有提供变量,这将设置count=0(创建默认值),否则它会将count设置为传入函数的任何内容
  • 你的check_solution()函数返回一个数字,但是当你用check_solution(user_answer, randsum, count)调用它时,你永远不会将这个返回值赋给任何东西/再次使用它。 您可以将此分配给变量(比如output),然后分配return output而不是return count

修复这些仍然没有完全解决问题,但是更接近(现在它被卡在“你回答x问题与1正确”):

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):
    count = 0
    if user_solution == solution:
        count += 1
        print("Correct.")

    else:
        print("Incorrect.")

    return count

def menu_option(index, count=0):
    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)
        output = check_solution(user_answer, randsum, count)
    return output

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 += 1
        correct = menu_option(option, correct)
        option = get_user_input()

    print("Exiting.")
    display_result(total, correct)

main()

我认为更简单的方法看起来像:

import random

def generate_question():
    num1 = random.randint(1, 25)
    num2 = random.randint(1, 25)
    question = '{} + {} = '.format(num1, num2)
    answer = num1 + num2
    return question, answer

def main():
    correct = 0
    total = 0
    option = True
    while option != '5':
        total += 1
        question, answer = generate_question()
        user_guess = int(input(question))
        if user_guess == answer:
            print('Correct.')
            correct += 1
        else:
            print('Incorrect.')
        option = input("Enter 5 to exit, or anything else to play again")
    print('You answered {} questions with {} correct'.format(total, correct))

main()
© www.soinside.com 2019 - 2024. All rights reserved.