Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

How do global variables work in Python? I know global variables are evil, I'm just experimenting.

This does not work in python:

G = None

def foo():

    if G is None:

        G = 1

foo()

I get an error:

UnboundLocalError: local variable 'G' referenced before assignment

What am I doing wrong?

1 Answer

0 votes
by (16.8k points)

You need the global statement:

def foo():

    global G

    if G is None:

        G = 1

In Python, variables that you assign to become local variables by default. You need to use global to declare them as global variables. On the other hand, variables that you refer to but do not assign to do not automatically become local variables. These variables refer to the closest variable in an enclosing scope.

Python 3.x introduces the non local statement which is analogous to global, but binds the variable to its nearest enclosing scope. For example:

def foo():

    x = 5

    def bar():

        nonlocal x

        x = x * 2

    bar()

    return x

This function returns 10 when called.

Related questions

0 votes
2 answers
0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.6k points)
+1 vote
2 answers
+1 vote
2 answers
asked May 29, 2019 in R Programming by Suresh (3.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...