Friday, January 10, 2025
HomeProgrammingPython - How to Use a Global Variable in a Function?

Python – How to Use a Global Variable in a Function?

In Python, to use a global variable inside a function, you can declare it as global within the function. This tells Python that you’re referring to the global variable and not creating a local one with the same name.

Steps to Use a Global Variable in a Function

  1. Define the variable outside any function (at the global level).
  2. Use the global keyword inside the function when you need to modify it.

Example: Using a Global Variable

# Define a global variable
count = 0

def increment():
    global count  # Declare that we are using the global variable 'count'
    count += 1    # Modify the global variable

increment()
increment()

print(count)  # Output: 2
  • Without the global keyword, the function would create a new local variable named count instead of modifying the global one.
See also  200 + core java interview questions and answers

Using a Global Variable Without Modifying It

If you only need to read the global variable and don’t modify it, you can access it directly without using the global keyword.

name = "Alice"  # Global variable

def greet():
    print(f"Hello, {name}!")  # Access the global variable

greet()  # Output: Hello, Alice!

Common Mistakes and Warnings

  1. Unintentional Shadowing of Global Variables: If you define a variable with the same name inside a function, Python treats it as a local variable unless explicitly declared as global.
    x = 10  # Global variable
    
    def modify():
        x = 20  # Local variable, doesn't affect the global 'x'
    
    modify()
    print(x)  # Output: 10
    
  2. Modifying Global Variables Without global: Attempting to modify a global variable inside a function without declaring it as global will raise an UnboundLocalError.
    counter = 0  # Global variable
    
    def increment():
        counter += 1  # Error: UnboundLocalError
    

    To fix this, add global counter before modifying it.

Alternative: Avoid Global Variables Using Function Parameters and Returns

Using global variables can make your code harder to debug and maintain. Instead, consider passing variables as function arguments and returning the results.

def increment(counter):
    return counter + 1

counter = 0
counter = increment(counter)
counter = increment(counter)

print(counter)  # Output: 2

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x