The variable from the function is not returned to the code and I get the error: name 'a' is not defined

Viewed 24

The variable from the function is not returned to the code.

Here is the Python code that causes the problem:

def test():
    a = 0
    return(a)
test()
print(a)

NameError: name 'a' is not defined

1 Answers

In your comment you said the function returns 0 and that's exactly what it should do, the way you're doing it isn't working because the definition of a is in the function and not in the global scope. You can either define a outside of the function or use print(test())

if you want to print the variable name you must consider the same thing for the scope but you can use:

variable_name = [k for k, v in locals().items() if v == 710][0] 
print("Your variable name is " + variable_name)

variable_name can also be returned in your function

Related