Home > OS >  How can a function access variables that are not defined inside the function?
How can a function access variables that are not defined inside the function?

Time:11-23

I recently started studying Python and I came across an example that I did not understand:

def teste():
    print(a, b)
    
a = 5
b = 4
teste() # Outputs '5 4'

What is happening here? Is teste() able to access a and b because those variables are globals?

CodePudding user response:

Short answer, yes. a and b are global variables in that sense. Long answer, as long as you keep the variable names on the right side of an assignment or just pass them to a function within a function, they'll act as global variables.

What's happening is that Python will first look in the local scope of that function for the variable names and only if it doesn't find them go for the next scope, which is the global scope in your example.

Function foo has no variable named a so Python searches in the next available scope

a = "global a"

def foo():
   # No variable 'a' in local scope of foo()
   # Getting value of 'a' from the scope where foo() is called
   print(a)

foo() # Prints "global a"

If you want to declare a variable as global inside your function, you can use the global keyword. With that you can set a new value to your now global variable:

a = "global a"

def foo():
    global a
    a = "Changed in function"

print(a)  # Prints "global a"
foo()  # assigns new value to a
print(a)  # Prints "Changed in function"

If you don't use the global keyword, as soon as you use the same variable name inside a function on the left side of an assignment, you are creating a local variable overshadowing the global variable with the same name:

a = "global a"

def foo():
    a = "local a"
    print(a)

print(a)  # Prints "global a"
foo()  # Prints "local a"
print(a)  # Prints "global a"
  • Related