tsleyson
0
Q:

python local variables

global var1
var1 = 'whatever'
21
trying to assign a global variable in a function will result in the function creating a new variable
with that name even if theres a global one. ensure to declare a as global in the function before any
assignment.

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a
4
'''Local variables are those that are defined in a block '''
a = 1 #This is NOT a local variable, this is a global variable
def add():
  b = 1 #This IS a local variable
  print(b)
add()
#If we tried to print(b) outside of the add() function, we would get an error
1

New to Communities?

Join the community