bhylu.com

Advertisements

Global Variables

A name defined at module level is available to functions that read it. Rebinding that name inside a function is a separate operation and should be a deliberate design choice.

Understand the idea

A function normally creates local bindings when it assigns a name. global tells it to rebind a module-level name instead. This can be useful for small scripts, but shared changing state makes tests and concurrent work harder to reason about. Passing values in and returning results is often clearer.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

booking_count = 0
def record_booking():
    global booking_count
    booking_count += 1
record_booking()
print(booking_count)

Read the result

The output is 1 because the function rebinds the module-level counter. Without global, this read-and-rebind pattern raises an UnboundLocalError.

Try one change

Rewrite the counter as a function that accepts a count and returns the next count without global.