Condition for Local and Global Variables in Python
Global Variables:
It is a variable defined outside any function or class.
Local Variables:
It is a variable that is defined within a function.
Step-by-Step Process
Global Variable:
Defined outside of any function or class.
Can be accessed and modified by any function in the program.
If you need to modify a global variable inside a function, use the global keyword.
Local Variable:
Defined inside a function.
Can only be accessed within that function.
Once the function execution is complete, the local variable is destroyed.
Sample Code
# Local variable
def example_function():
num = 10
print("Local variable inside function:", num)
example_function()
print()
# Global variable
message = "Hi my name is, Kumar"
def greet():
print("Global variable inside of function calling:")
print(message)
greet()
print("Global variable outside of function calling:")
print(message)