【问题标题】:input variable inside of a function output outside of function函数内部的输入变量 函数外部的输出
【发布时间】:2018-12-15 06:31:18
【问题描述】:

我对编码很陌生,我正在制作一个冒险“游戏”来帮助我学习。玩家需要进行一些对话并做出决定,这会导致不同的选择,其中两个会询问他们的名字。我似乎无法让 player_name 变量出现在下一个函数中,它只是保持空白。我只是希望它作为一个全局变量,我可以在整个游戏中继续使用它。

   
player_name = ("")

def path_2():
    print("I found you lying in the hallway.")
    print("Maybe I should have left you there...")
    player_name = input("What is your name? : ")
    return player_name

def path_1():
    print("It's a pleasure to meet you.")
    print ("My name is Azazel. I am the warden of this place.")
    print ("I found you lying in the hallway,")
    print ("bleeding profusely from you head there.")
    print ("")
    player_name = input("What is your name? : ")
    return player_name

def quest():
    print(("This is a long story ")+str(player_name)+(" you'll have to be patient."))
    enter()

【问题讨论】:

    标签: python object variables global new-operator


    【解决方案1】:

    当您执行 player_name = input("What is your name? : ") 时,您在函数范围内重新定义 player_name,因此它不再指向全局变量,您可以做什么是:

    def path_2():
      print("I found you lying in the hallway.")
      print("Maybe I should have left you there...")
      global player_name 
      player_name = input("What is your name? : ")
    

    请注意,您不需要返回玩家名称,因为您正在修改全局变量。

    【讨论】:

      【解决方案2】:

      在函数中使用相同变量之前使用全局关键字

      【讨论】:

        【解决方案3】:

        这里有几个概念需要进一步完善才能完成这项工作。第一个是变量的范围。二是函数的参数和返回值。简而言之(您应该对此进行更多研究),您在函数中创建的变量在该函数之外是不可见的。如果您 return 一个值,那么您可以从调用位置捕获它。使用全局变量是可能的,但通常不是最好的方法。考虑:

        def introduce():
          player_name = input("tell me your name: ")
          print("welcome, {}".format(player_name))
          return player_name
        def creepy_dialogue(p_name, item):
          print("What are you doing with that {}, {}?".format(item, p_name))
        
        # start the story and get name
        name = introduce()
        
        weapon = "knife"
        creepy_dialogue(name, weapon)
        

        【讨论】:

          猜你喜欢
          • 2021-08-26
          • 1970-01-01
          • 2022-11-27
          • 1970-01-01
          • 2021-08-20
          • 1970-01-01
          • 1970-01-01
          • 2013-11-10
          • 1970-01-01
          相关资源
          最近更新 更多