简体   繁体   中英

input variable inside of a function output outside of function

I'm pretty new to coding and I'm making an adventure "game" to help me learn. The player has a bit of dialogue to get through and a decision to make, which leads to different choices, two of which ask for their name. I can't seem to make the player_name variable appear in the next function, it just stays blank. I just want it as a global variable where I can continue to use it throughout the game.

 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() 

When you're doing player_name = input("What is your name? : "), you're re-defining player_name in the scope of your function, so it's no longer pointing to the global variable, what you could do is:

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? : ")

Notice that you don't need to return player name, because you're modifying the global variable.

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

You have a couple of concepts here that you'll need to sharpen up on to make this work. The first is the scope of a variable. The second is parameters and return values of functions. Briefly (you should research this more), the variables you create in a function are not visible outside that function. If you return a value, then you can catch it from the calling location. Using global variables is possible, but usually not the best approach. Consider:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM