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