J.D.
J.D.

Reputation: 169

Variable forgotten when calling a function

This program I wrote ran into an infinity and crashed. The program contains a big for loop. I managed to locate which iteration of the for loop the problem occurred in. To help debug, I created a Boolean variable that would be true only for the bad iteration. Unfortunately, it isn't working as expected.

I've managed to come up with a simple example that reproduces the problem.

def troublemaker():
    print(trouble)

def program(iterations):
    for itnumber in range(iterations):
        print(itnumber)
        if itnumber==3:
            trouble=True
        else:
            trouble=False
        print(trouble)
        troublemaker()

program(5)

I expect the following output:

0
False
False
1
False
False
2
False
False
3
True
True
4
False
False

However I instead get:

...
3
True
False
...

Why?

Upvotes: 0

Views: 126

Answers (1)

htmler
htmler

Reputation: 380

Due to this line, trouble=True python thinks that trouble is a local variable and will not assign the value to trouble in the global scope. That's why you got that error.

Global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function.

From Python Docs:

All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

You can fix this using global keyword like that:

trouble = False

def troublemaker():
    print(trouble)

def program(iterations):

    global trouble

    for itnumber in range(iterations):
        print(itnumber)
        if itnumber==3:
            trouble=True
        else:
            trouble=False
        print(trouble)
        troublemaker()

program(5)

Upvotes: 1

Related Questions