Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Global Variable | Variable Scope
Intermediate Python Techniques
course content

Course Content

Intermediate Python Techniques

Intermediate Python Techniques

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

bookGlobal 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.

1234567
age = 20 def birthday_greet(): print(f"Happy B-Day! You are {age}! (local message)") birthday_greet() print("Global message", age)
copy

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:

12345678
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)
copy

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 <strong class="go98639658">global</strong> keyword.

12345678910
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)
copy

Click the button below the code to check solution.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
some-alt