Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

What is Local and Global Variables in Python?

Local and Global Variables in Python

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)
Screenshots
  • Local and Global Variables