What is the difference between local and global variables in Python?

0204

In Python, the difference between local and global variables lies in their scope and accessibility:

  1. Global Variables:

    • Defined outside of any function.
    • Accessible from any function within the same module.
    • Can be modified inside a function using the global keyword.

    Example:

    global_var = "I'm global"
    
    def access_global():
        print(global_var)  # Accessing global variable
    
    access_global()  # Output: I'm global
  2. Local Variables:

    • Defined within a function.
    • Accessible only within that function.
    • Cannot be accessed outside the function.

    Example:

    def local_variable_example():
        local_var = "I'm local"
        print(local_var)  # Accessing local variable
    
    local_variable_example()  # Output: I'm local
    # print(local_var)  # This would raise a NameError

In summary, global variables can be accessed from anywhere in the module, while local variables are confined to the function in which they are defined.

0 Comments

no data
Be the first to share your comment!