Python Scope · Exercises
Core Python

Python Scope Exercises

4 exercises that build on the Python Variable Scope lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Scope is the region of a program where a name can be seen; Python looks a name up in the Local, Enclosing, Global and Built-in scopes, in that order. By the end you can tell local variables from global ones, predict which value a name refers to using the LEGB rule, fix an UnboundLocalError, and avoid global state by returning values. You will practise: Predict: local or global?; Fix the UnboundLocalError; Update a high score with global; Refactor away the global.

0 / 4 completed

Python Scope practice exercises

1. Predict: local or global?

Predict the output Easy

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
level = "global"

def show():
    level = "local"
    print(level)

show()
print(level)

2. Fix the UnboundLocalError

Fix the bug Medium

This code crashes with an UnboundLocalError. Fix it without using the global keyword: change withdraw to withdraw(current, amount) so it takes the current balance as a parameter and returns the new balance. Then update the call so that balance ends up as 70.

Your code
balance = 100

def withdraw(amount):
    balance = balance - amount
    return balance

balance = withdraw(30)
print(balance)

3. Update a high score with global

Write code Medium

Complete submit_score(score). If score is higher than the global high_score, update the global high_score and return True. Otherwise leave it unchanged and return False.

Your code
high_score = 0

def submit_score(score):
    # update the global high_score when score beats it
    # return True for a new high score, otherwise False
    pass

print(submit_score(50), high_score)
print(submit_score(30), high_score)

4. Refactor away the global

Write code Hard

sell() currently changes the global stock. Rewrite it as sell(current_stock, quantity) that does not use any global variable. It returns the new stock, or returns current_stock unchanged (and may print Not enough stock) when quantity is larger than the stock. Then update the two calls to stock = sell(stock, ...) so that stock ends up as 7.

Your code
stock = 10

def sell(quantity):
    global stock
    if quantity > stock:
        print("Not enough stock")
        return
    stock -= quantity

sell(3)
sell(20)
print(stock)

Next lessonPython Closures

More Python Variable Scope examples · All Python exercises