【问题标题】:How do I use a variable so that it is inside and outside of a function如何使用变量使其位于函数内部和外部
【发布时间】:2016-07-11 05:55:12
【问题描述】:

我想知道如何在函数中使用变量,然后在函数之外使用。 这是我的代码的一部分,它应该在答案正确时将分数加 1,然后打印出总分(有多个函数,所以我需要分数在函数之外):

score=0
def Geography(score):
#Question 1
qa1= input("What is the capital of England? ")
if qa1.lower() == ("london"):
    print ("Correct you gain 1 point")
    score=score+1
else:
    print ("Incorrect")

Geography(score)
print ("This quiz has ended. Your score is " , score, ".")

如您所见,我尝试使用参数,但无论该人是否正确回答,代码最后仍将分数返回为 0。

【问题讨论】:

    标签: function variables if-statement arguments python-3.4


    【解决方案1】:

    尝试在变量“score”之前使用“global”并在“def Geography():”函数中再次访问它。此代码适用于代码中的所有“def”函数:

    global score
    score = 0
    
    
    def Geography():
        # Question 1
        global score
        qa1 = input("What is the capital of England? ")
        if qa1.lower() == ("london"):
            print("Correct you gain 1 point")
            score = score + 1
        else:
            print("Incorrect")
    
    
    Geography()
    print("This quiz has ended. Your score is ", score, ".")
    

    【讨论】:

      【解决方案2】:

      从函数中返回score并将其分配回score

      score=0
      def Geography(score):
          #Question 1
          qa1= input("What is the capital of England? ")
          if qa1.lower() == ("london"):
              print ("Correct you gain 1 point")
              score=score+1
          else:
              print ("Incorrect")
          return score
      
      score = Geography(score)
      print ("This quiz has ended. Your score is " , score, ".")
      

      【讨论】:

      • 这会导致代码重复,但仍然显示分数为 0
      • 它是如何导致代码重复的?我刚刚对其进行了测试,并且效果很好。您的代码中是否还有更多未提出问题的内容?
      • 对不起,代码不再重复,这是我的错。用户必须在多个函数之间进行选择,因此在调用该函数时,它位于 if 语句中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2019-12-12
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多