函数内的输入变量 函数外的输出

input variable inside of a function output outside of function

我对编码还很陌生,我正在冒险 "game" 来帮助我学习。玩家需要进行一些对话并做出决定,这会导致不同的选择,其中两个会询问他们的名字。我似乎无法让 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()

当您执行 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? : ")

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

在函数中使用同一个变量之前使用 global 关键字

您在这里有几个概念,您需要加强这些概念才能完成这项工作。第一个是变量的 scope。第二个是函数的参数和 return 值。简而言之(您应该对此进行更多研究),您在函数中创建的变量在该函数之外是不可见的。如果你 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)