Why is my variable inside a function not defined even if it's global?

Viewed 70

So I made a function to open sites:

import webbrowser

def go_to_url(link):
    
    global YT, Reddit, SO
    YT = 'youtube.com'
    Reddit = 'reddit.com'
    SO = 'stackoverflow.com'
    webbrowser.open(link)

go_to_url(YT)

No syntax error when running, but returns result:

NameError: name 'YT' is not defined

Later I tried to define the variables outside the function and it worked:

import webbrowser

def go_to_url(link):
   webbrowser.open(link)

YT = 'youtube.com'
Reddit = 'reddit.com'
SO = 'stackoverflow.com'

go_to_url(YT)

I just don't understand why can't I define it inside my function, even if they are global anyway. Please explain it to me, thanks in advance!

1 Answers

The issue you have here is that the variable isn't defined until you actually run the function, and so YT doesn't exist at the time you're trying to make the call. As an example:

In [144]: def make_vars():
     ...:     global hello
     ...:     hello = "world"
     ...:

In [145]: print(hello)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-145-1cd80308eb4c> in <module>
----> 1 print(hello)

NameError: name 'hello' is not defined

In [146]: make_vars()

In [147]: print(hello)
world
Related