Global Variables
What Is a Global Variable?
- A global variable in Python is a variable with a scope that extends across the entire program. It can be accessed anywhere, inside or outside functions.
Example of a Global Variable:
Here's a simple example of a global variable:
pythonx = 'hello world - global' def myFunction(): print(x) myFunction() print(x)Output:
hello world - global hello world - global- In this example,
xis a global variable accessible both insidemyFunction()and outside in the main program.
Using the global Keyword:
When you want to update a global variable inside a function, you need to use the
globalkeyword. Without it, Python will treat the variable as local to the function.pythonx = 'hello world - 0' def myFunction(): global x x = 'hello world - 1' print(x) myFunction() print(x)Output:
hello world - 1 hello world - 1- By declaring
xas global insidemyFunction(), we ensure the function updates the global variablexrather than creating a new local variable.
Exercises:
- Global Variable Access:
Create a global variable and access it inside a function and outside the function.
pythony = 'global variable example' def exampleFunction(): print(y) exampleFunction() print(y)
- Updating Global Variable:
Write a function that updates a global variable.
pythonz = 5 def updateGlobalVariable(): global z z = 10 updateGlobalVariable() print(z) # Output: 10
Summary:
- Global variables in Python have a scope that spans the entire program. The
globalkeyword is used to modify a global variable inside a function. Practice defining and updating global variables to understand their usage and scope!