pythonfunctionvariablesgame-development

How can I store user input as a username in a text-based python game without the program starting with an input prompt?


I'm creating a text based RPG for my programming class. The game is made up of many custom functions. When I call the function player_World(), a prompt appears for the user/player to name their character and is stored as the variable player_Name. In a following line, it welcomes the player to the game and uses the name they input.

As this variable is stored in the player_World() function, it is undefined in following functions such as east_Village() and cannot be used.

How can I store the player's username so that the variable can be used in any of my custom functions?

I've seen some posts about global variables but I am unsure if that's the right move here.

So far I have tried defining player_Name = input("What will this hero's new name be?\n") in my #import section at the top of my file. Of course, this means that when running the program, it asks for the user's input first (prior to the "prologue" of my game), which isn't ideal. Defining the variable within each function would be redundant, so I am at a loss of what to do here.

I hope my question makes sense, thank you in advance!


Solution

  • Here's a simplest-form version of the question:

    def foo():
        x = input()
    
    def bar():
        print(x)
    

    Without using a global variable, a good rule of thumb is to ask, "how can I give each function the inputs it needs, and get the outputs back?"

    Typically, you can put the "inputs" as arguments and the outputs as what's returned. In this minimal example, we can solve the problem like so:

    def foo():
        return input()
    
    def bar(name):
        print(name)
    

    To link this together, we can do this:

    
    If __name__ == "__main__":
        name = foo()
        bar(name)