In Python, global variables are variables declared outside any function. Once defined, they can be accessed and used throughout the program — both inside and outside functions.

🧾 What is a Global Variable?

A global variable lives in the global scope — meaning it’s available to all functions in your script.

✅ Example: Using a Global Variable Inside a Function

language = "Python"

def show_language():
    print("We love", language)

show_language()

🖥 Output:

We love Python

🔎 The variable language was defined outside the function and used inside — no problem at all!


🚫 Local vs Global: Same Name, Different Scope

If you create a variable with the same name inside a function, Python treats it as local to that function. It won’t affect the global one.

🧪 Example: Local Variable with Same Name

language = "Python"

def change_language():
    language = "Java"
    print("Inside function:", language)

change_language()
print("Outside function:", language)

🖥 Output:

Inside function: Java
Outside function: Python

🔐 The outer language remains unchanged because the function used a new local variable with the same name.


🌐 The global Keyword

Sometimes, you may want to modify a global variable from within a function. To do this, use the global keyword.

🧰 Example: Creating a Global Variable from Inside a Function

def set_course():
    global course
    course = "Python Basics"

set_course()
print("Course name is:", course)

🖥 Output:

Course name is: Python Basics

✏️ Example: Updating an Existing Global Variable

course = "Advanced Python"

def update_course():
    global course
    course = "Full Stack Python"

update_course()
print("Updated course name:", course)

🖥 Output:

Updated course name: Full Stack Python

💡 Without the global keyword, the function would only create a local copy, not update the original.


🔁 Quick Recap: When to Use global

SituationWhat to Do
Access a global variable inside function✅ Just use it directly
Modify a global variable✅ Use global keyword
Create a global variable from inside✅ Use global keyword
Avoid accidental overwrites❌ Don’t reuse variable names unnecessarily

Scroll to Top