0

I am an absolute newbie when it comes to python and am learning by doing via my own text adventure game.

I have some code that enables the user to input their name:

# player name
def playerName():
    name = ""
    name = input("Before we begin, what is your name, warrior? ") 
    print("\n")
    print("Welcome {}, now be on your way!".format(name))
    print("\n")

This works as it is supposed to in the game. The player inputs their name and the game continues. However, I would like to be able to print the player's input later on in a different function and keep running the error message that name is undefined.. So I am trying to store this input as a global variable. I think that is the correct method, yes?

I have read up about storing functions as a global variable but these are always already specified by the programmer, i.e. name = sarah.

How do I store the input so that I can print it later on? I thought print("string" + name) would have been enough later on. But I have obviously misunderstood something.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Cl4rify
  • 3
  • 1
  • 3
  • 1
    Globals, especially modifiable globals, break modularity, so if you're not careful the program soon becomes one big tangled mess that's difficult to analyze. So try to keep their use to a minimum. Group related items together in collections like lists and dicts, or custom classes. – PM 2Ring May 20 '18 at 10:31

2 Answers2

3

You can declare the variable as global and access it whenever and whereever you want. For example:

# player name

name = ""

def playerName():
    global name
    name = input("Before we begin, what is your name, warrior? ")
    print("\n")
    print("Welcome {}, now be on your way!".format(name))
    print("\n")

def printname():
    print(name)

playerName()
printname()

Output:

Before we begin, what is your name, warrior? hari


Welcome hari, now be on your way!


hari 

Explanation:

Declare a variable name at first of the file and access it using global keyword. So the value stored in that variable is accessed by multiple functions as mentioned in the code

  • @Cl4rify: This is tested in my local PC and added. Please let me know if you need more information –  May 20 '18 at 10:07
2

At the top of your file, create the variable:

name = None

# other functions....

def function_you_want_to_use_name_in():
    global name
    print(name)

def main():
    global name
    name = input("Before we begin, what is your name, warrior? ") 
    print("\n")
    print("Welcome {}, now be on your way!\n".format(name))

You don't have to include global name in function_you_want_to_use_name_in if you're just printing the value; theres no other variable named name in the function, so python uses the global value. I usually include it anyways, as it makes it clearer whats happening.

Sean Breckenridge
  • 1,932
  • 16
  • 26