Using global and nonlocal statement
In Python, the global and nonlocal keywords are used to specify the scope of variables inside functions.
The global keyword is used to indicate that a variable is a global variable, which means that it is accessible from anywhere in the program, including inside functions. When a variable is defined as global, it can be modified inside a function and the changes will be reflected outside the function as well.
For example, consider the following code that defines a global variable and modifies it inside a function:
csharp
x = 0
def increment():
global x
x += 1
increment()
print(x) # Output: 1
In this example, the increment() function modifies the global variable x by incrementing it by 1. The global keyword is used inside the function to indicate that x is a global variable.
The nonlocal keyword, on the other hand, is used to indicate that a variable is a nonlocal variable, which means that it is not local to the current function but is defined in an enclosing function. When a variable is defined as nonlocal, it can be accessed and modified inside the current function, but any modifications will also be reflected in the enclosing function.
For example, consider the following code that defines a nonlocal variable and modifies it inside a nested function:
python
def outer():
x = 0
def inner():
nonlocal x
x += 1
inner()
print(x)
outer() # Output: 1
In this example, the outer() function defines a local variable x and a nested function inner() that modifies it using the nonlocal keyword. When the outer() function is called, it calls inner() and then prints the value of x, which has been modified by the nested function.
In general, it is a good practice to avoid using global and nonlocal variables as much as possible, since they can make code harder to read and debug. Instead, it is better to use local variables and pass data between functions using parameters and return values.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer