Variable scope

a = 5 # a is a global variable
b = a + 1 # b is a global variable

def fun(d): # d, as a parameter, is a local variable
  c = 7 + a + d # c is a local variable
  print(c)


fun(1)
13

Scope rules

  • Variables in different scopes can have the same names!
a = 5

def fun1():
  a = 1
  print(a)

def fun2():
  a = 3
  print(a)

print(a)
5

Scope rules

  • Local variables have precedence over global variables!
a = 5

def fun1():
  a = 1
  print(a)

def fun2():
  a = 3
  print(a)

fun1()
fun2()
print(a)
1
3
5

Example

  • What are the local and global variables in the following program?
x=4

def main():
  f1(3)
  f2(3)
  print(x)

def f1(a):
  x = 10
  print('f1',a+x)
  
def f2(a):
  c=10
  print('f2',a+x+c)

main()
f1 13
f2 17
4