-4
def theproblem():
    print(username)

def main():
    username = "myUserName"
    theproblem()

it's unable to request the username string. tried to solve this like 2 days, if someone can help, big thanks.

name 'username' is not defined 
  • you really need to take a step back and learn about basic scoping rules (`username ` is local to your function `main`, you could make it global but that is a bad practice), and passing values to functions as arguments, and returning those values to the caller. – juanpa.arrivillaga Jun 30 '20 at 22:14
  • Read up on [Tutorial - 9.2. Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) – stovfl Jul 01 '20 at 08:01

3 Answers3

2

You need to pass in something as a parameter for your function:

def theproblem(username):
    print(username)

def main():
    username = "myUserName"
    theproblem(username)





I understand what you were trying to do, but since the variable is defined inside the function, it is only accessible in that particular function, unless you return the variable or use global:

def theproblem():
    print(username)

def main():
    global username
    username = "myUserName"
    theproblem()

This is definitely not recommended, as it is considered a bad practice:
https://stackoverflow.com/a/19158418/13552470

Red
  • 26,798
  • 7
  • 36
  • 58
0

In my side, username in main() is a local variable, so if we want to access it for another function, we can use global syntax, like bellow:

def theproblem():
    print(username)
def mainFunc():
    global username
    username = "myUserName"
    theproblem()

mainFunc()

or something like this:

def mainFunc():
    global username
    username = "myUserName"
def theproblem():
    mainFunc()
    print(username)

theproblem()
monti
  • 311
  • 2
  • 9
0

Another approach to this problem, that hasn't been mentioned, would be to nest the functions:

def main():
    def theproblem():
        print(username)

    username = "myUserName"
    theproblem()

main()

which should work as you expect.

cdlane
  • 40,441
  • 5
  • 32
  • 81