Python Interview Question

How to Declare a Global Variable in Python

How to Declare a Global Variable in Python
How to Declare a Global Variable in Python

Global Variable in Python

In Python, variables can have different scopes depending on where they are created. A global variable is a variable defined outside a function and can be accessed from different parts of a program. Understanding global variables is important when working with functions and managing data across different parts of your Python program.

In this tutorial, we will learn what a global variable is, how to access it inside a function, how local variables work, and how to modify a global variable using the global keyword.

How to Declare a Global Variable in Python

YT:- DecodeIT

What is a Global Variable in Python?

A global variable in Python is a variable that is defined outside any function. Because it is created in the global scope, it can generally be accessed from both inside and outside functions.

Let’s look at a simple example.

Example 1: Define and Use a Global Variable

def func():
    print("Inside the function:", var)


var = "Declaring the Global Variable"

func()

print("Outside the function:", var)

Output

Inside the function: Declaring the Global Variable
Outside the function: Declaring the Global Variable

In this example, var is created outside the function, so it has global scope. The func() function can access the variable, and it can also be accessed outside the function.

Accessing a Global Variable Inside a Function

A global variable can be accessed inside a function as long as there is no local variable with the same name that changes how Python resolves that name.

message = "Hello from Python"

def show_message():
    print(message)

show_message()

Output

Hello from Python

Here, message is defined outside the function. The function can read and print its value without using the global keyword.

Global and Local Variables in Python

A local variable is created inside a function and normally exists only within that function. If a local variable has the same name as a global variable, the local variable is used inside that function.

Example 2: Local and Global Variable with the Same Name

def func():
    var = "Local Variable"
    print("Inside the function:", var)


var = "Global Variable"

func()

print("Outside the function:", var)

Output

Inside the function: Local Variable
Outside the function: Global Variable

In this example, there are two variables named var. The variable inside func() is local, while the variable outside the function is global. Changing the local variable does not change the global variable.

Modifying a Global Variable Inside a Function

There is an important difference between reading and modifying a global variable inside a function. If you assign a value to a variable inside a function, Python normally treats that variable as local to the function.

For example:

def func():
    var = var + " Global Variable"
    print(var)


var = "Python Tutorial"

func()

This produces an error because Python treats var inside the function as a local variable, but the local variable is referenced before it has been assigned a value.

Output

UnboundLocalError: local variable 'var' referenced before assignment

Using the global Keyword

To modify a global variable from inside a function, Python provides the global keyword. It tells Python that the variable inside the function refers to the variable defined in the global scope.

Example 3: Modify a Global Variable Using global

def func():
    global var

    var = var + " Global Variable"

    print("Inside the function:", var)


var = "Python Tutorial"

func()

print("Outside the function:", var)

Output

Inside the function: Python Tutorial Global Variable
Outside the function: Python Tutorial Global Variable

In this example, global var tells Python that the function should use the existing global variable instead of creating a new local variable. Therefore, the change made inside the function is also visible outside the function.

Global Variable with Numbers

The global keyword can also be used when modifying numeric variables.

count = 10

def increase_count():
    global count
    count += 5

increase_count()

print(count)

Output

15

The function changes the global value from 10 to 15.

Combining Global and Local Variables

Let’s look at an example that shows how different functions can access, create, and modify variables with different scopes.

var = 10

def func1():
    print("Inside the first function:", var)


def func2():
    var = 15
    print("Inside the second function:", var)


def func3():
    global var
    var += 3
    print("Inside the third function:", var)


print("Global value:", var)

func1()

print("Global value:", var)

func2()

print("Global value:", var)

func3()

print("Global value:", var)

Output

Global value: 10
Inside the first function: 10
Global value: 10
Inside the second function: 15
Global value: 10
Inside the third function: 13
Global value: 13

The first function only reads the global variable. The second function creates a separate local variable, so the global value remains unchanged. The third function uses the global keyword and changes the global variable itself.

Global vs Local Variables

FeatureGlobal VariableLocal Variable
DefinedOutside a functionInside a function
ScopeGlobal scopeLocal scope
AccessCan be accessed from appropriate parts of the programNormally available only inside its function
Modification inside functionRequires global for assignment to the global nameCan be assigned directly

Best Practices for Global Variables

Global variables can be useful, but they should be used carefully. Too many global variables can make a program harder to understand, maintain, and debug.

  • Use global variables only when they are actually needed.
  • Give variables clear and meaningful names.
  • Avoid using the same name for local and global variables when it may cause confusion.
  • Use constants for values that should not normally change. Python commonly represents constants using uppercase names.
  • Prefer function parameters and return values when they can make data flow clearer.

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here

Conclusion

A global variable in Python is defined outside a function and can be accessed from different parts of the program. A function can normally read a global variable, but assigning a new value to that variable inside the function requires the global keyword.

Local variables, on the other hand, are created inside functions and normally remain within their local scope. Understanding the difference between local and global variables helps you write Python programs with clearer variable scope and behavior.

Frequently Asked Questions

What is a global variable in Python?

A global variable is a variable defined outside a function. It belongs to the global scope and can generally be accessed from different parts of the program.

How do you declare a global variable in Python?

Define the variable outside a function. For example, count = 10 creates a global variable named count.

What is the use of the global keyword in Python?

The global keyword tells Python that a variable inside a function refers to a variable defined in the global scope, allowing the function to modify it.

Can a function access a global variable?

Yes. A function can normally read a global variable if there is no local variable with the same name affecting the lookup.

What is the difference between local and global variables?

A global variable is defined outside a function and has global scope, while a local variable is created inside a function and normally has scope limited to that function.

Keywords

Global Variable in Python, how to declare a global variable in Python, local variable in Python, global keyword in Python, use global variable in function Python, how to change global variable in function Python, global variable in Python example, local and global variables in Python with example, global variable in Python W3Schools, global variable in Python class, Python global function, Python global variable across files, global variable Python tutorial, Python variable scope, Python global keyword example

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

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

Chat with us