Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Global Variables in Python: Accessing and Modifying Global Data | Understanding Variable Scope in Python
Intermediate Python Techniques

book
Global Variables in Python: Accessing and Modifying Global Data

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)
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:

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

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 1

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt