AttributeError · Exercises
Core Python

AttributeError Exercises

4 exercises that build on the Python AttributeError 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: An AttributeError means you used a dot to reach a variable or method that the object does not have, usually because the object is a different type than you assumed or the name is misspelled. By the end you can read an AttributeError message, find the real type behind it, and fix the five most common causes. You will practise: Make names a list; Predict the attribute checks; Fix the missing attribute; Read optional attributes safely.

0 / 4 completed

AttributeError practice exercises

1. Make names a list

Fix the bug Easy

names should end up as the list ["Asha", "Ravi", "Meena"], but the code raises an AttributeError. Fix the first line so the appends work.

Your code
names = "Asha"
names.append("Ravi")
names.append("Meena")
print(names)

2. Predict the attribute checks

Predict the output Easy

Read the code and type exactly what it prints.

Read this code
class Student:
    def __init__(self, name):
        self.name = name

student = Student("Asha")
scores = []

print(hasattr(student, "name"))
print(hasattr(student, "grade"))
print(hasattr(scores, "append"))
print(getattr(student, "grade", "none"))
print(scores.sort())

3. Fix the missing attribute

Fix the bug Medium

Account(owner, balance) should keep both values so account.balance and account.deposit(amount) work. At the moment reading balance raises an AttributeError. Fix the class without changing the method names.

Your code
class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

account = Account("Asha", 100)
print(account.deposit(50))

4. Read optional attributes safely

Write code Hard

Write describe(obj). It must return the string "<name> (<city>)" using obj.name and obj.city. If the object has no city attribute, use "unknown". If it has no name attribute, use "anonymous". It must not raise for any object, and must not modify it.

Your code
def describe(obj):
    return f"{obj.name} ({obj.city})"

class Person:
    def __init__(self, name):
        self.name = name

print(describe(Person("Asha")))

Next lessonPython ModuleNotFoundError: No module named

More Python AttributeError examples · All Python exercises