Python lesson 26
Scope. Where a Variable Lives
Why the thing you made inside a function vanishes outside it.
Inside Stays Inside
A variable made inside a function only exists while that function is running. When it finishes, the variable is gone. Variables made outside can be read from inside. But to change one, you have to say so with global, which you almost never should.
score = 0 # global. Everyone can read it
def play():
bonus = 10 # local. Only exists in here
print(score) # fine, reading is allowed
play()
print(bonus) # error: bonus is gone
score = 0
def play():
bonus = 10
print("Inside, bonus is", bonus)
print("Inside, score is", score)
play()
print("Outside, score is", score)
Did It Change?
score = 5
def add_points():
score = 100
add_points()
print(score)
Reading Is Different
lives = 3
def show():
print("Lives:", lives)
show()
The Right Way to Change It
Instead of reaching outside, take a value in and hand a new one back. Run it.
def add_points(current, points):
return current + points
score = 5
score = add_points(score, 20)
print("Score is now", score)
Keep the Function Honest
This function takes what it needs and returns what it made. Nothing outside it can be surprised.
def level_up(level, xp):
new_level = level + 1
new_xp = xp + 100
return new_level, new_xp
level, xp = 2, 350
level, xp = level_up(level, xp)
print("Level", level, "with", xp, "XP")
What global Really Does
global lets a function change an outer variable. Run it, then think about why this is usually a bad idea.
coins = 0
def collect():
global coins
coins = coins + 1
collect()
collect()
print("Coins:", coins)
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.