NameError · Exercises
Core Python

NameError Exercises

4 exercises that build on the Python NameError 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: A NameError means Python looked for a name (a variable, function or module) in every scope it checks and found nothing called that, so the line cannot run. By the end you can read a NameError traceback, identify which of six common causes triggered it and fix it. You will practise: Fix the misspelled variable; Predict the NameError output; Add the missing import and constant; Fix grade names and scope.

0 / 4 completed

NameError practice exercises

1. Fix the misspelled variable

Fix the bug Easy

This code should store 10% of the cart subtotal in tax and print it. It raises a NameError. Fix the misspelling without renaming subtotal.

Your code
cart = [12.5, 8, 4.5]
subtotal = sum(cart)
tax = subtotl * 0.1
print(tax)

2. Predict the NameError output

Predict the output Easy

Read the code and type exactly what it prints. Then press Check.

Read this code
def make_label():
    label = "sale"
    return label

try:
    print(label)
except NameError:
    print("no label yet")

label = make_label()
print(label)
del label

try:
    print(label)
except NameError as err:
    print(err)

3. Add the missing import and constant

Write code Medium

packs_needed(items) should return how many packs of PACK_SIZE you need to hold items items (round up). It crashes with NameErrors. Add the missing import and define the constant PACK_SIZE = 6 at the top of the file.

Your code
def packs_needed(items):
    return math.ceil(items / PACK_SIZE)

print(packs_needed(13))

4. Fix grade names and scope

Write code Hard

Make letter_grade(score) return "A" for 90 and above, "B" for 75 and above and "C" for anything lower. Make collect_grades(scores) return the list of letters in order, and store the result for [95, 80, 40] in grades before printing it. The starter hits an UnboundLocalError (a kind of NameError) and a NameError.

Your code
def letter_grade(score):
    if score >= 90:
        grade = "A"
    elif score >= 75:
        grade = "B"
    return grade

def collect_grades(scores):
    grades = []
    for score in scores:
        grades.append(letter_grade(score))

collect_grades([95, 80, 40])
print(grades)

Next lessonPython SyntaxError

More Python NameError examples · All Python exercises