5.2 Scope
Scope determines where a variable can be accessed. Understanding scope helps you reason about variables inside and outside functions.
Local variables
Variables defined inside a function are local variables. They can only be accessed inside that function.
python
def swap(a, b):
a, b = b, a
print("inside swap(): a = %d, b = %d" % (a, b))
def main():
a, b = 1, 2
print("Before: a = %d, b = %d" % (a, b))
swap(a, b)
print("After: a = %d, b = %d" % (a, b))
if __name__ == "__main__":
main()Output:
text
Before: a = 1, b = 2
inside swap(): a = 2, b = 1
After: a = 1, b = 2Loading interactive lab...
Loading concept check...
Global variables
Variables defined outside functions are global variables. To modify a global variable inside a function, use global.
python
a, b = 1, 2
def swap():
global a, b
a, b = b, a
print("inside swap(): a = %d, b = %d" % (a, b))
def main():
print("Before: a = %d, b = %d" % (a, b))
swap()
print("After: a = %d, b = %d" % (a, b))
if __name__ == "__main__":
main()Global variables are sometimes useful, but overusing them makes programs harder to debug.
Loading concept check...
Loading practice...