,

Variable Scope in Python (Part-12)

Posted by

Local Scope

A variable declared inside a function is local to that function and can only be used within that function. These variables are created when the function is called and destroyed when the function exits.

Example:

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

my_function()  # Output: 10
print(x)  # Error: NameError: name 'x' is not defined

Global Scope

A variable declared outside of all functions is global and can be accessed anywhere in the code after its declaration.

Example:

x = 10  # Global variable

def my_function():
    print(x)  # Accessing global variable

my_function()  # Output: 10
print(x)  # Output: 10

Global Keyword

The global keyword is used to modify a global variable within a function. Without using the global keyword, you cannot assign a value to a global variable within a function.

Example:

x = 10  # Global variable

def my_function():
    global x
    x = 20  # Modifying global variable

my_function()
print(x)  # Output: 20

Nonlocal Keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function.

Example:

def outer_function():
    x = "local"

    def inner_function():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner_function()
    print("outer:", x)

outer_function()
# Output:
# inner: nonlocal
# outer: nonlocal

Summary

  • Local Scope: Variables declared inside a function.
  • Global Scope: Variables declared outside of all functions.
  • Global Keyword: Used to modify global variables within a function.
  • Nonlocal Keyword: Used to modify variables in the enclosing scope of a nested function.

Local Scope in Python

A variable created inside a function belongs to the local scope of that function and can only be used inside that function. Variables defined within a function are known as local variables, and their scope is limited to the function in which they are created.

Example 1: Basic Local Scope

def myfunc():
    x = 300  # Local variable
    print(x)

myfunc()

In this example, the variable x is defined inside the function myfunc(). It is a local variable and its scope is limited to the function. When the function is called, it prints the value of x.

Example 2: Local Scope with Nested Functions

def outerfunc():
    x = 300  # Local variable in outer function

    def innerfunc():
        y = 200  # Local variable in inner function
        print("Inner function:", y)
    
    innerfunc()
    print("Outer function:", x)

outerfunc()

In this example, x is a local variable in the outerfunc() function, and y is a local variable in the innerfunc() function. Both variables are accessible only within their respective functions.

Example 3: Local Variable Shadows Global Variable

x = 100  # Global variable

def myfunc():
    x = 300  # Local variable shadows the global variable
    print(x)

myfunc()
print(x)

In this example, there is a global variable x with a value of 100. Inside the function myfunc(), there is a local variable x with a value of 300. The local variable shadows the global variable within the function scope. When the function is called, it prints the local x, and when the global x is printed outside the function, it prints the global value.

Example 4: Local Scope with Lists and Loops

def myfunc():
    fruits = ["apple", "banana", "cherry"]  # Local variable

    for fruit in fruits:
        print(fruit)

myfunc()

Global Scope in Python

A variable that is created outside of any function or block of code is known as a global variable. Global variables can be accessed from any function or block of code within the same program. However, if you want to modify a global variable inside a function, you must use the global keyword.

Example 1: Basic Global Scope

x = 300  # Global variable

def myfunc():
    print(x)

myfunc()
print(x)

In this example, x is a global variable defined outside of any function. The function myfunc() can access and print the value of x. The global variable x is also accessible outside the function.

Example 2: Modifying Global Variable using global Keyword

x = 300  # Global variable

def myfunc():
    global x
    x = 200  # Modify global variable
    print(x)

myfunc()
print(x)

In this example, the global keyword is used inside the function myfunc() to indicate that x refers to the global variable x. The function modifies the value of the global variable x, and the change is reflected outside the function as well.

Example 3: Using Global Variable in Nested Functions

x = 300  # Global variable

def outerfunc():
    def innerfunc():
        print("Inner function:", x)
    
    innerfunc()
    print("Outer function:", x)

outerfunc()
print("Global scope:", x)

In this example, x is a global variable. Both the outerfunc() and innerfunc() can access and print the value of the global variable x.

Example 4: Global Variable with Lists and Loops

fruits = ["apple", "banana", "cherry"]  # Global variable

def myfunc():
    for fruit in fruits:
        print(fruit)

myfunc()

In this example, fruits is a global variable defined as a list of fruit names. The function myfunc() can access and iterate through the list, printing each fruit.

Example 5: Read and Modify Global Variable

count = 0  # Global variable

def increment():
    global count
    count += 1  # Modify global variable

def get_count():
    print(count)

increment()
get_count()
increment()
get_count()

In this example, count is a global variable initialized to 0. The function increment() uses the global keyword to modify the global variable count. The function get_count() prints the current value of count. Each call to increment() increases the value of count by 1.

Global Keyword in Python

The global keyword is used to declare a variable inside a function as global. This means that the variable can be accessed and modified both inside and outside the function.

Example 1: Using the Global Keyword

x = 300  # Global variable

def myfunc():
    global x
    x = 200  # Modify global variable inside function

myfunc()
print(x)  # This will print 200

In this example, x is a global variable. The global keyword inside the function myfunc() allows the function to modify the global variable x. The change is reflected outside the function as well.

Example 2: Global Variable Inside a Function

def myfunc():
    global x
    x = 200  # Declare and assign a global variable inside function

myfunc()
print(x)  # This will print 200

In this example, x is declared as a global variable inside the function myfunc(). After calling the function, x is accessible outside the function with the assigned value of 200.

Example 3: Using Global Variable Across Functions

x = 300  # Global variable

def func1():
    global x
    x = 200  # Modify global variable

def func2():
    print(x)  # Access global variable

func1()
func2()  # This will print 200

In this example, x is a global variable. The function func1() modifies the global variable x, and the function func2() accesses and prints the modified value of x.

Example 4: Global Variable in Nested Functions

x = 300  # Global variable

def outerfunc():
    def innerfunc():
        global x
        x = 200  # Modify global variable inside nested function
    
    innerfunc()

outerfunc()
print(x)  # This will print 200

In this example, x is a global variable. The global keyword is used inside the nested function innerfunc() to modify the global variable x.

Example 5: Using Global Keyword with Lists

fruits = ["apple", "banana", "cherry"]  # Global variable

def add_fruit():
    global fruits
    fruits.append("orange")  # Modify global list inside function

add_fruit()
print(fruits)  # This will print ["apple", "banana", "cherry", "orange"]

In this example, fruits is a global variable defined as a list. The global keyword inside the function add_fruit() allows the function to modify the global list fruits.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x