The important thing to consider here is the scope of the variable and/or function names you're using. Global scope means everything can see it, whether it's at the top level, inside a function, or even inside a method, which is inside a class.
Local scope means it's locked within the context of that block, and nothing outside of the block can see it. In your case, that block is a function.
(Note that this is a mild simplification and more complex rules exist around modules and includes, but this is a reasonable starter for 10...).
In your example above, the function has been defined at the global level, so its name, func_1
has global scope (you might also say that it is in the "global namespace". That means that anything can see it, including code inside other functions.
Conversely, the variable name
has local scope, inside func_1
, which means it is only visible inside func_1
, and nowhere else.
When you return name
, you're passing the value of name
back to whatever called that function. That means that the user_input = func_1()
receives the value that was returned and stores it in a new variable, called user_input
.
The actual variable name
is still only visible to func_1
, but that value has been exposed to outside functions by return
ing it.
Edit: As requested by @Chris_Rands:
There is a function in Python that will give you a dictionary containing of all the global variables currently available in the program.
This is the globals()
function. You can check something is at global scope by seeing if it is in this dictionary:
def func_1():
name = input('What is your name?')
def func_2():
print(name)
func_1_is_global = 'func_1' in globals() # value is 'True'
name_is_global = 'name' in globals() # value is 'False'
One additional edit for completeness: I state above that you're passing the value of name
back. This is not strictly true as Python is pass-by-reference, but the waters get murky here and I didn't want to confuse the issue. More details here for the interested observer: How do I pass a variable by reference?