← All lessons

global: changing the outer variable

Sign in · Sign up

Lesson 6.7

Without global, an assignment inside a function creates a local variable, and the outer one stays as it was. With global the function changes the outer one itself:

count = 0

def increment():
    global count
    count += 1

increment()
increment()
print(count)   # 2

The line global count goes at the start of the function, before the first use. nonlocal does the same for nested functions — that's the next step.

The check sets the number times. Create a counter count = 0, a function increment() with global count, call it times times and print count.

Hint

An assignment inside a function creates a local variable instead of changing the outer one.

The word global allows changing the outer one: global count is written inside the function, before count += 1. Then call the function times times in a loop and print count.