Course Content
Intermediate Python Techniques
Intermediate Python Techniques
Global Variable
Not all objects are accessible everywhere in a script. Scope - a portion of the program (code) where an object or variable may be accessed.
A global variable is not declared inside any functions; it resides in the global scope, which is the main body of the script. This means a global variable can be accessed inside and outside the function.
age = 20 def birthday_greet(): print(f"Happy B-Day! You are {age}! (local message)") birthday_greet() print("Global message", age)
Click the button below the code to check solution.
Pretty easy, we can use global variables in global and local (inside function) scopes.
Now, let's continue to improve our birthday_greet()
function. If it's the person's birthday, we need to increase their age by 1.
We cannot change the global variable inside the function, so let's try to pass the global variable age
as an argument:
age = 20 def birthday_greet(age): age += 1 print(f"Happy B-Day! You are {age}! (local message)") birthday_greet(age) print("Global message", age)
Click the button below the code to check solution.
In this case, the global variable remains unchanged, and we are working with a local variable named age
.
The next example shows that we can change the global variable within a local scope by using the global keyword.
age = 20 def birthday_greet(): global age # Added 'global' keyword age += 1 print(f"Happy B-Day! You are {age}! (local message)") birthday_greet() print("Global message", age)
Click the button below the code to check solution.
Thanks for your feedback!