Global And Local Variables

Global Variables

In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a global variable.

Example of a Global Variable:

Python

x = 10  # This is a global variable

def my_function():
    print(x)  # This function can access the global variable 'x'

my_function()  # Output: 10
print(x)       # Output: 10

Local Variables

A local variable is a variable defined inside a function. It is only accessible within the scope of that specific function. Once the function finishes execution, the local variable is destroyed, and its value cannot be accessed from outside the function.

Example of a Local Variable:

Python

def my_function():
    y = 20  # This is a local variable
    print(y)

my_function()  # Output: 20
# print(y)     # This will cause an error because 'y' is a local variable and is not defined outside the function

Key Differences

  • Scope: Global variables have a global scope (accessible everywhere), while local variables have a local scope (accessible only within the function they are defined in).
  • Lifetime: Global variables exist as long as the program is running. Local variables are created when the function is called and destroyed when the function completes.
  • Modification: To modify a global variable inside a function, you must use the global keyword. You do not need a special keyword to modify a local variable within its own function.

Python

# A global variable for a game score
score = 0

def add_points(points):
    # The 'global' keyword is needed to modify the global variable
    global score
    score += points

add_points(10)
print(score)  # Output: 10

Python

# A global variable
count = 0

def increment():
    # This creates a new local variable named 'count', it does NOT change the global one.
    count = 100
    print(f"Inside function, local count is: {count}")

def correct_increment():
    # This modifies the global 'count'
    global count
    count = 100
    print(f"Inside function, global count is: {count}")

increment()
print(f"Outside function, global count is: {count}") # Output: 0

correct_increment()
print(f"Outside function, global count is: {count}") # Output: 100

The globals() Function

The globals() function in Python returns a dictionary representing the current global symbol table. This table contains all the global variables, functions, and classes defined in the current module. You can use it to inspect or even modify global variables.

  • How it works: When you call globals(), it gives you a dictionary where the keys are the names of the global variables and the values are their corresponding objects.

Python

x = 10
y = "hello"

def my_func():
    pass

global_vars = globals()
print(global_vars['x'])      # Output: 10
print('y' in global_vars)    # Output: True

You can also use it to add or change global variables, but this is generally not recommended as it can make your code hard to follow.


The locals() Function

The locals() function returns a dictionary representing the current local symbol table. This table contains all the local variables in the current scope.

  • How it works: When called inside a function, locals() returns a dictionary of the variables defined within that function. When called at the top level of a module (outside any function), it returns the same dictionary as globals().

Python

def my_function():
    a = 1
    b = "world"
    local_vars = locals()
    print(local_vars['a'])      # Output: 1
    print('b' in local_vars)    # Output: True

my_function()

The dictionary returned by locals() should be treated as read-only. Modifying it might not affect the local variables themselves in some Python implementations, so it’s best to only use it for inspection.

Similar Posts

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • Python Exception Handling – Basic Examples

    1. Basic try-except Block python # Basic exception handlingtry: num = int(input(“Enter a number: “)) result = 10 / num print(f”Result: {result}”)except: print(“Something went wrong!”) Example 1: Division with Zero Handling python # Handling division by zero error try: num1 = int(input(“Enter first number: “)) num2 = int(input(“Enter second number: “)) result = num1 /…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

Leave a Reply

Your email address will not be published. Required fields are marked *