Python – Global Variables
1. What is a Global Variable?
A global variable is a variable that is:
-
Created outside a function
-
Can be used anywhere in the program
In simple words:
👉 A global variable is available for everyone.
2. Creating a Global Variable
You create a global variable outside any function.
Example
x = 10 # global variable
def my_function():
print(x)
my_function()
print(x)
Output:
10
10
Here:
-
xis created outside the function -
It works inside and outside the function
3. Using Global Variable Inside a Function
A function can read a global variable without any problem.
Example
name = "Python" # global variable
def show_name():
print("Language:", name)
show_name()
Output:
Language: Python
4. Changing a Global Variable Inside a Function
To change a global variable inside a function,
you must use the global keyword.
Example
count = 5 # global variable
def increase():
global count
count = count + 1
increase()
print(count)
Output:
6
Without global, Python will give an error.
5. What Happens Without global Keyword?
❌ Wrong Example
x = 10
def change():
x = 20 # local variable
change()
print(x)
Output:
10
Here:
-
xinside function is local -
Global
xis not changed
6. Global vs Local Variable (Simple Difference)
Example
x = 100 # global
def test():
x = 50 # local
print(x)
test()
print(x)
Output:
50
100
7. When to Use Global Variables?
✔ When value is shared by many functions
✔ When value should stay same everywhere
❌ Avoid too many global variables
They can make code confusing.
8. Common Beginner Mistakes
❌ Forgetting global Keyword
total = 10
def add():
total = total + 5 # error
✔ Correct:
def add():
global total
total = total + 5
9. Simple Practice Examples
Example 1: Global Counter
counter = 0
def increase():
global counter
counter += 1
increase()
increase()
print(counter)
Example 2: Global Message
message = "Hello"
def show():
print(message)
show()
10. Summary (Global Variables)
✔ Global variables are created outside functions
✔ Can be used anywhere
✔ Use global to change value inside function
✔ Avoid overuse of global variables
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Python Local Variables
-
Python Functions (easy)
-
Python Scope (global vs local)
-
Practice questions with answers
Just tell me 😊
