In this tutorial, we will learn how to use global variables in Python. Global variables are those variables that are defined outside of a function and can be accessed by any function throughout the program.
Global variables can be useful when different functions need to share the same data or use the same configuration settings.
Let’s walk through the process of using global variables in Python step-by-step.
Step 1: Define a Global Variable
The first step in using global variables in Python is defining a variable outside of a function. Let’s create a global variable called language
and assign it the value “English.”
1 |
language = "English" |
This variable can now be accessed by any function in the Python program.
Step 2: Access the Global Variable in a Function
To access the global variable inside a function, you can simply use its name. Here’s an example of a function named greet
that uses the global variable language
:
1 2 3 |
def greet(): greeting = "Hello" if language == "English" else "Hola" print(greeting) |
Step 3: Modify a Global Variable Inside a Function
If you need to modify the value of a global variable inside a function, you must use the global
keyword before the variable name. Without the global
keyword, Python will treat the variable as a local variable and will not modify the actual global variable.
Here’s an example function, change_language
, that modifies the value of the language
global variable:
1 2 3 |
def change_language(new_language): global language language = new_language |
Step 4: Test the Global Variable in a Script
Here’s a simple script that demonstrates how we can use the global variable language
, the greet
function, and the change_language
function to greet the user in different languages:
1 2 3 4 5 6 |
# Initial greeting in English greet() # Change language to Spanish and greet the user again change_language("Spanish") greet() |
The output of this script will be:
Hello Hola
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
language = "English" def greet(): greeting = "Hello" if language == "English" else "Hola" print(greeting) def change_language(new_language): global language language = new_language # Initial greeting in English greet() # Change language to Spanish and greet the user again change_language("Spanish") greet() |
Conclusion
Using global variables in Python can be a convenient way to share data or configuration settings among different functions in your program. By following the steps outlined in this tutorial, you can define, access, and modify global variables in your Python scripts effectively. Keep in mind that global variables can lead to unintended side effects and should be used cautiously, as a better programming practice would be to utilize function parameters and return values to pass data between functions.