Search code examples
pythonfunctionvariablesscopeglobal-variables

Difference between a global variable and variable defined in main?


I am confused on the difference between creating a global variable vs defining a variable in main. I have a very specific example that I would like explained. Here is the specific code:

def f():
    username = input("Please enter your username: ")
    print("Thank you for entering your username")

#I want to be able to use the "username" variable outside of the "f" function
#and use it multiple times throughout my code
print(f"Your username is: {username}")

Here is the solution I initially thought was correct:

def f():
    global username
    username = input("Please enter your username: ")
    print("Thank you for entering your username")
f()
print(f"Your username is: {username}")

Here is the solution that I was told was the actual correct/preferred way:

def f():
    username = input("Please enter your username: ")
    print("Thank you for entering your username")
    return username

username = f()
print(f"Your username is: {username}")

The reasoning for the second solution was that it is better to return a variable and creating a global variable using the global keyword is very discouraged/should be avoided, but I'm confused because I thought the second solution also creates a variable that is defined in the global scope since they are defining the variable in main (here is the article I read which confirmed this concept of global vs main variables, if someone can confirm this is correct it would be helpful as well since I have multiple questions regarding this).

I am confused on this Python concept and why the second solution is a better/preferred method of solution. Can someone explain?


Solution

  • The second one does create a global variable. The critical difference, though, is that your function does not rely on it. The user of your function could also write

    def f():
        username = input("Please enter your username: ")
        print("Thank you for entering your username")
        return username
    
    name_of_user = f()
    print(f"Your username is: {name_of_user}")
    

    Note that there is no dependence on the name your function uses to store the input and the name the caller uses to receive it. Your local variable username does not exist outside your function, and your function knows nothing about how the value it returns will be used, or even it is used at all.