首页 > 解决方案 > Python: getting variable from user function

问题描述

im trying to make a simple text game for a school project and also make the code somewhat clean therefore I started using functions and classes.

The problem is im stuck on trying to access a variable from a function that asks the user for their username.

Here is my code

def playername():
    print("What is your name?")
    playername = input()

how can I access the playername variable without running the whole function again so once I run it at the start and get the username I can use that same input username later on in the code?

标签: pythonfunction

解决方案


store it as a variable outside of function. for example string playerName = playername() and add return playername to the end of the function "playername"

def playername():
    print("What is your name?")
    playername = input()
    return playername

def main():
    playerName = playername()
    print(playerName)

main()

推荐阅读