【问题标题】:How do you change a variable in a function to then be used in the main code?如何更改函数中的变量,然后在主代码中使用?
【发布时间】:2016-09-30 17:34:52
【问题描述】:

我对 Python 还是很陌生,但在弄清楚以下问题时遇到了一些麻烦:

import random
import sys

print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
    print("This quiz is not for your age.")
    sys.exit(0)
else :
    print("Great! Let's begin.\n")

quizQuestions = ["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"]
quizAnswers = ["99", "79", "88", "12.5", "0"]
quizSync = list(zip(quizQuestions, quizAnswers))
random.shuffle(quizSync)
quizQuestions, quizAnswers = zip( * quizSync)
questionNumber = 1
quizScore = 0

def displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore):
    print("Question " + str(questionNumber) + ": " + quizQuestions[questionNumber - 1] + "\n")
    questionAnswer = str(input())
    if questionAnswer == quizAnswers[questionNumber - 1]:
        print("\nCorrect!\n")
        quizScore += 1
    else :
        print("\nIncorrect! The answer is: " + quizAnswers[questionNumber - 1] + "\n")

while questionNumber < 6:
    displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)
    questionNumber += 1

print("You have a total score of: "+str(quizScore))

如果玩家答对问题,我希望函数“displayQuestion”中的变量“quizScore”加一。但是,测验完成后,即使玩家答对了,最后的打印功能也总是打印分数为 0。

【问题讨论】:

  • 你得到“正确!”打印出来的?
  • 是的,我得到“正确!”和印有相应答案的“不正确”。
  • 一方面,displayQuestion 不返回字符串,那你为什么要在print(displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)) 中打印呢?
  • 在你的函数中全局化 quizScore 。

标签: python function variables


【解决方案1】:

你必须在函数内部将它声明为全局变量,这样它才能在全局范围内修改变量

def displayQuestion(quizQuestions, quizAnswers, questionNumber):
    global quizScore    
    ...
    quizScore += 1

话虽如此,您通常应该尽可能避免使用全局变量,并尝试重新设计程序以将变量作为参数传递并返回值,或者使用类来封装数据。

【讨论】:

  • 你的意思是不是类似这样的:pastebin.com/Dd0BiFag
  • 您不能同时将quizScore 作为参数传入并将其用作全局变量。要么将其作为参数传入,然后将其作为返回变量返回,要么将其设为全局变量并就地修改
【解决方案2】:

虽然这不是最短的答案,但它是使用另一个全局变量。相反,它将向您展示如何通过使用 Object Oriented Programming (OOP) 来避免使用全局变量 (which are considered harmful)。为此,您问题中的大部分代码都可以封装到下面名为MathQuiz 的单个类中。

除了摆脱几乎所有的全局变量外,它还提供了一个可用的模板供您创建任意数量的独立数学测验。

import random
import sys

class MathQuiz:
    def __init__(self, questions, answers):
        quizSync = list(zip(questions, answers))
        random.shuffle(quizSync)
        self.quizQuestions, self.quizAnswers = zip(*quizSync)
        self.quizScore = 0

        print("Welcome to this Maths quiz.")
        self.playerName = str(input("Please enter your name: "))
        self.playerAge = int(input("Please enter your age: "))
        if self.playerAge > 10:
            print("Great! Let's begin.\n")
        else :
            print("This quiz is not for your age.")
            sys.exit(0)

    def run(self):
        for questionNumber in range(len(self.quizQuestions)):
            self._displayQuestion(questionNumber)

        print("You have a total score of: " + str(self.quizScore))

    def _displayQuestion(self, questionNumber):
        print("Question " + str(questionNumber) + ": "
              + self.quizQuestions[questionNumber-1]
              + "\n")
        questionAnswer = str(input())
        if questionAnswer == self.quizAnswers[questionNumber-1]:
            print("\nCorrect!\n")
            self.quizScore += 1
        else :
            print("\nIncorrect! The answer is: "
                  + self.quizAnswers[questionNumber-1]
                  + "\n")

quiz = MathQuiz(["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"],
                ["99", "79", "88", "12.5", "0"])
quiz.run()

【讨论】:

    猜你喜欢
    • 2014-04-26
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多