Function Scope

Global Scope

  1. # global variable
  2. x = 10
  3. def func():
  4. print(x)
  5. func()
  6. #ans: 10

Local Scope

  1. # local variable
  2. def func():
  3. y = 20
  4. print(y)
  5. func()
  6. #ans: print(y) # NameError

Global Keyword

  1. # modify global variable
  2. count = 0
  3. def increment():
  4. global count
  5. count += 1
  6. increment()
  7. #ans: count is 1

Nonlocal Keyword

  1. # modify enclosing scope
  2. def outer():
  3. x = 10
  4. def inner():
  5. nonlocal x
  6. x = 20
  7. inner()
  8. return x
  9. result = outer()
  10. #ans: 20

Shadowing

  1. # local shadows global
  2. x = 10
  3. def func():
  4. x = 5
  5. print(x)
  6. func()
  7. #ans: 5
  8. print(x)
  9. #ans: 10

Exercises - Part 1

  1. # what is printed?
  2. x = 5
  3. def func():
  4. print(x)
  5. func()
  6. #ans: 5

Exercises - Part 2

  1. # what happens?
  2. x = 5
  3. def func():
  4. x = 10
  5. func()
  6. print(x)
  7. #ans: 5 (local x doesn't affect global)

Exercises - Part 3

  1. # global keyword?
  2. x = 5
  3. def func():
  4. global x
  5. x = 10
  6. func()
  7. print(x)
  8. #ans: 10

Exercises - Part 4

  1. # can you do this?
  2. def func():
  3. print(x)
  4. x = 5
  5. func()
  6. #ans: UnboundLocalError

Exercises - Part 5

  1. # nonlocal?
  2. def outer():
  3. x = 5
  4. def inner():
  5. nonlocal x
  6. x = 10
  7. inner()
  8. return x
  9. outer()
  10. #ans: 10

Exercises - Part 6

  1. # nested functions?
  2. def outer():
  3. x = 5
  4. def inner():
  5. return x
  6. return inner()
  7. outer()
  8. #ans: 5

Exercises - Part 7

  1. # what is x?
  2. x = 1
  3. def func():
  4. x = x + 1
  5. func()
  6. #ans: UnboundLocalError

Exercises - Part 8

  1. # parameter scope?
  2. def func(x):
  3. x = 10
  4. x = 5
  5. func(x)
  6. print(x)
  7. #ans: 5

Exercises - Part 9

  1. # global in nested?
  2. x = 5
  3. def outer():
  4. def inner():
  5. global x
  6. x = 10
  7. inner()
  8. outer()
  9. print(x)
  10. #ans: 10

Exercises - Part 10

  1. # closure?
  2. def outer(x):
  3. def inner(y):
  4. return x + y
  5. return inner
  6. f = outer(10)
  7. f(5)
  8. #ans: 15

Google tag (gtag.js)