Scope
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Introduction to Variable Scope
In Python, scope refers to the region of code where a variable can be accessed. Understanding scope is crucial for writing bug-free functions.
When you create a variable inside a function, it's called a local variable. This variable only exists inside that function and cannot be accessed from outside.
def train_codemon():
# codemon_name is a LOCAL variable
codemon_name = "Aquachu"
print(f"Training {codemon_name}!")
train_codemon()
# print(codemon_name) # Error variable not definedIn this example, codemon_name only exists inside the train_codemon() function. If you try to use it outside (uncomment the last line), Python will give you an error saying the variable doesn't exist.
Why Local Variables?
Local variables help keep functions independent and prevent accidental changes to variables. Each function has its own "workspace" with its own variables.
Exercise 2 — Identifying Variable Scope
Look at this code. What will happen when we try to print level outside the function?
def evolve_codemon():
level = 20
print(f"Codemon evolved at level {level}!")
evolve_codemon()
print(level)level doesn't exist outside the functionHint : Remember that variables created inside a function are local to that function and cannot be accessed from outside.
Exercise 3 — Global Variables
Variables created outside of any function are called global variables. These variables can be accessed from anywhere in your code, including inside functions.
trainer_name = "Pierre" # global var
def greet_trainer():
# We can READ global variables inside functions
print(f"Hello, {trainer_name}!")
def battle():
# Both functions can access the same global variable
print(f"{trainer_name} is battling!")
greet_trainer()
battle()
print(f"Trainer: {trainer_name}")In this example, trainer_name is a global variable. Both greet_trainer() and battle() can read its value, and we can also use it outside any function.
Reading vs. Modifying
You can READ global variables inside functions without any issues. However, MODIFYING them requires special syntax (the global keyword), which we'll learn about soon.
Exercise 4 — Create a Function with Local Variables
Complete the function to calculate and return the total power of a Codémon. The variables should be local to the function.
Hint : The first blank should create a local variable to store the multiplier. The second blank should return the calculated value from the function.
Exercise 5 — Variable Shadowing
When a local variable has the same name as a global variable, the local variable "shadows" (hides) the global one inside the function. What will this code print?
codemon_type = "Water"
def check_type():
codemon_type = "Fire"
print(f"Inside function: {codemon_type}")
check_type()
print(f"Outside function: {codemon_type}")Hint : Think about which variable is used in each context. Inside the function, Python uses the local variable. Outside, it uses the global variable.
Exercise 6 — Variable Lifetime
Variables have a lifetime - they are created at a certain point and destroyed at another point in your program.
- Local variables: Created when the function is called, destroyed when the function returns - Global variables: Created when the program starts, destroyed when the program ends
def battle_codemon():
# hp is created HERE
hp = 100
print(f"Battle started! HP: {hp}")
hp = hp - 30
print(f"After attack! HP: {hp}")
# hp is destroyed HERE when function ends
# Each call creates a NEW hp variable
battle_codemon()
print("---")
battle_codemon()Notice that each time we call battle_codemon(), a new hp variable is created with the value 100. The variable from the first call doesn't exist anymore when we make the second call.
Fresh Start
Each function call gets its own set of local variables. This is why functions are reliable - they always start with the same initial state unless you pass different arguments.
Exercise 7 — Fix the Scope Issue
Complete the code.
Hint : To use a value from inside a function, you need to return it and store the result when calling the function.
Exercise 8 — The global Keyword
If you need to modify a global variable from inside a function, you must use the global keyword to tell Python you want to work with the global variable, not create a new local one.
total_battles = 0
def win_battle():
global total_battles
total_battles = total_battles + 1
print(f"Battles won: {total_battles}")
win_battle()
win_battle()
win_battle()
print(f"Total: {total_battles}")The global total_battles line tells Python: "I want to modify the global variable, not create a local one." Without it, Python would create a new local variable instead.
Try not to use global
While global might be useful, it's generally better to use parameters and return values. Global variables can make code harder to understand and debug. Use them only when necessary.
Exercise 9 — When to Use global
Which of these situations requires the global keyword?
Hint : Remember that you can read global variables without any special keyword, but modifying them requires the global keyword.
Exercise 10 — Match Scope Concepts
Match each scope-related concept with its correct description:
global