我对编码还很陌生,我正在制作一个冒险“游戏”来帮助我学习。玩家需要进行一些对话并做出决定,这导致了不同的选择,其中两个要求他们的名字。我似乎无法使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()
答案 0 :(得分:0)
当您执行player_name = input(“您的名字是什么?:”)时,您将在函数范围内重新定义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? : ")
请注意,由于您正在修改全局变量,因此无需返回玩家名称。
答案 1 :(得分:0)
在函数中使用相同变量之前先使用全局关键字
答案 2 :(得分:0)
在这里您需要完善一些概念才能完成这项工作。第一个是变量的作用域。第二个是函数的参数和返回值。简要地说(您应该对此进行更多研究),在函数中创建的变量在该函数外部不可见。如果您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)