Python Function Scope

  • Read
  • Discuss

In Python, the scope of a variable refers to the portion of the program where the variable can be accessed. Every function has its own scope, which includes the variables defined within the function and any parameters passed into the function. Variables defined outside of a function are said to have global scope and can be accessed from anywhere within the program.

When a variable is defined within a function, it is only accessible within that function. This is known as a local variable. Here is an example:

def my_function():
    x = 10 # local variable
    print(x)

my_function()  # Output: 10
print(x)

The above code will raise an error because x is not accessible outside of the function

A global variable, on the other hand, can be accessed from anywhere within the program. Here is an example:

x = 10  # global variable

def my_function():
    print(x)

my_function()
print(x) 

The output of the above code will be

When a variable with the same name is defined within a function, it creates a new local variable that shadows (hides) the global variable of the same name within that function. Here is an example:

x = 10  # global variable

def my_function():
    x = 20  # local variable that shadows the global variable
    print(x)

my_function()
print(x)  

The output of the above code will be

In case you want to access the global variable within the function, you can use the global keyword to indicate that you want to refer to the global variable, instead of creating a new local variable with the same name.

x = 10  # global variable

def my_function():
    global x
    x = 20  # modifying the global variable
    print(x)

my_function()
print(x)

The output of the above code will be

It’s important to note that modifying a global variable within a function may have unintended consequences and is generally considered bad practice. Instead, it’s recommended to pass the global variable as an argument to the function and return a new value if necessary.

In this tutorial, I’ve covered the basics of function scope in Python, including the difference between local and global variables and how variables with the same name can shadow each other.

Leave a Reply

Leave a Reply

Scroll to Top