Scope & Keywords
Scope
what variables do I have access to - Local scope → inside function. - Parent scope → enclosing function. - Global scope → module-level. - Built-in scope → Python built-ins (sum, max, min , etc..).
a = 1 #global scope
def parent():
a = 15 #parent scope
def some_func():
a = 10 #function scope or local scope
return a
return some_func
Keywords
Global keyword
- Allows modifying global variables inside functions.
- For global access or scope
total = 0
def counter():
global total
total += 1
return total
counter()
counter()
print(counter())
(or)
def counter1(total):
total += 1
return total
print(counter1(counter1(counter1(total))))
Non local keyword
- Allows modifying parent scope variables inside nested functions.
- For parent access or scope
def outer():
x = 'local'
def inner():
nonlocal x
x = 'nonlocal'
print('inner:', x)
inner()
print('outer:', x)
outer()