In Python, variables can be categorized into global, local, and nonlocal based on their scope. Understanding these scopes is crucial for writing clean and efficient code. Let’s delve into each type:
Variables are containers that store information that can be manipulated and referenced later by the programmer within the code.
In python, the programmer does not need to declare the variable type explicitly, we just need to assign the value to the variable.
Example:
name = "Abhishek" #type str
age = 20 #type int
passed = True #type bool
PythonIt is always advisable to keep variable names descriptive and to follow a set of conventions while creating variables:
- Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable name must start with a letter or the underscore character.
- Variables are case sensitive.
- Variable name cannot start with a number.
Example:
Color = "yellow" #valid variable name
cOlor = "red" #valid variable name
_color = "blue" #valid variable name
5color = "green" #invalid variable name
$color = "orange" #invalid variable name
PythonSometimes, a multi-word variable name can be difficult to read by the reader. To make it more readable, the programmer can do the following:
Example:
NameOfCity = "Mumbai" #Pascal case
nameOfCity = "Berlin" #Camel case
name_of_city = "Moscow" #snake case
PythonPython Scope of Variable
The scope of the variable is the area within which the variable has been created. Based on this a variable can either have a local scope or a global scope.
Python Global Variables
Global variables are declared outside of any function or block and can be accessed from anywhere within the program. They have a global scope, meaning they are visible to all functions.
Example:
x = 10 # This is a global variable
def print_global():
print(x) # Accessing the global variable within a function
print_global() # Output: 10
PythonIn this example, x
is a global variable accessible inside the print_global()
function without any special declaration.
A global variable is created in the main body of the code and can be used anywhere within the code. Such a variable has a global scope.
Example:
icecream = "Vanilla" #global variable
def foods():
vegetable = "Potato" #local variable
fruit = "Lichi" #local variable
print(vegetable + " is a local variable value.")
foods()
print(icecream + " is a global variable value.")
print(fruit + " is a local variable value.")
PythonOutput:
Potato is a local variable value.
Vanilla is a global variable value.
PythonPython Local Variables
Local variables are declared within a function or block and can only be accessed within that function or block. They have a local scope, meaning they are visible only within the function or block where they are defined.
Example:
def print_local():
y = 20 # This is a local variable
print(y)
print_local() # Output: 20
# Attempting to access y outside the function will result in an error
PythonHere, y
is a local variable and can only be accessed within the print_local()
function.
A local variable is created within a function and can be only used inside that function. Such a variable has a local scope.
Example:
icecream = "Vanilla" #global variable
def foods():
vegetable = "Potato" #local variable
fruit = "Lichi" #local variable
print(vegetable + " is a local variable value.")
print(icecream + " is a global variable value.")
print(fruit + " is a local variable value.")
foods()
PythonOutput:
Potato is a local variable value.
Vanilla is a global variable value.
Lichi is a local variable value.
PythonPython Nonlocal Variables
Nonlocal variables in Python are used in nested functions to modify variables in the outer (enclosing) function’s scope. They are neither global nor local but belong to a scope in between. Nonlocal variables can be accessed and modified by the inner nested function.
Example:
pythonCopy code
def outer():
z = 30 # This is a nonlocal variable
def inner():
nonlocal z
z = 40 # Modifying the value of the nonlocal variable
print("Inner function:", z)
inner()
print("Outer function:", z)
outer()
PythonIn this example, z
is a nonlocal variable. The inner()
function modifies the value of z
, and these changes are reflected in the outer function as well.
Understanding global, local, and nonlocal variables is essential for writing modular and maintainable code in Python. By properly scoping variables, you can avoid unexpected behaviors and make your code more readable and organized.
Conclusion
Understanding the concepts of global, local, and nonlocal variables is fundamental to writing efficient and maintainable Python code. By properly scoping variables, you can control their visibility and accessibility within different parts of your program. Global variables provide a way to share data across different functions, while local variables keep data encapsulated within specific functions, reducing the risk of unintended modifications. Nonlocal variables offer a middle ground, allowing nested functions to modify variables in the enclosing function’s scope. By using these variable scopes effectively, you can write cleaner, more organized code that is easier to understand and maintain.
Frequently Asked Questions
Ans: If a variable is declared both globally and locally within a function, the local variable takes precedence over the global variable within that function’s scope. However, outside the function, the global variable remains unaffected.
Q2. Can global variables be modified within a function without using the global keyword?
Ans: Yes, global variables can be accessed within a function without using the global keyword. However, if you want to modify a global variable inside a function, you need to use the global keyword to explicitly declare the variable as global.
Q3. Can nonlocal variables be accessed from outside the nested function?
Ans: No, nonlocal variables can only be accessed and modified within the nested function in which they are declared as nonlocal. They cannot be accessed from outside the nested function.
Q4. Is it recommended to extensively use global variables in Python programs?
Ans: No, it is not recommended to use global variables extensively in Python programs because they can lead to code that is difficult to debug and maintain. Instead, it is better to use local variables whenever possible to encapsulate data within functions and minimize side effects.