Scope and the LEGB Rule
Names are looked up in Local, Enclosing, Global, then Built-in scope.
Easy
gain = 2 # global
def amplify(x):
offset = 1 # local
return x * gain + offset
def counter():
global gain # rebind the global (use sparingly)
gain += 1
Assigning to a name inside a function makes it local unless declared global or nonlocal.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.