Asiman Data School

Module 1, topic 7, week 4, Tuesday

Modules and packages; introduction to Object-Oriented Programming

Classes and objects, encapsulation, abstraction, inheritance and polymorphism, and using modules and packages

Introduction: classes and objects, modules and packages

A beginner-friendly guide to Object-Oriented Programming (OOP) and to modules and packages. It starts with the four big ideas of OOP in plain words, with real-life examples and no code: encapsulation, abstraction, inheritance and polymorphism. Then it shows how to write classes and create objects in Python, and comes back to each of the four ideas with code. After that it explains modules and packages: how to use code that other people wrote, and how to organise your own. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.

You should already know variables, data types, if/else, loops, functions, lists, dictionaries and try/except.

What you will learn

  1. 1.What OOP is, and the four ideas behind it, each with real-life examples
  2. 2.What a class and an object are, and how to write __init__, attributes and methods
  3. 3.Encapsulation: keeping data and the actions on it together, and protecting the data
  4. 4.Abstraction: hiding the details behind a simple method
  5. 5.Inheritance: building a new class on top of an existing one
  6. 6.Polymorphism: the same method name doing the right thing for each kind of object
  7. 7.Modules and packages: import, from ... import, as, your own module, installing packages
  8. 8.15 solved problems and practice problems

1The four ideas of OOP in plain words

1.1What is Object-Oriented Programming?

Until now our programs had two separate things: data (variables, lists, dictionaries) and functions that work on the data. In a small program that is fine. In a big program it becomes hard to see which function belongs to which data.

Object-Oriented Programming puts the two together. An object is one thing that has:

  • data about itself (called attributes), and
  • actions it can do (called methods).

Real-life picture: a car. It has data (color, speed, amount of fuel) and actions (start, drive, brake). You do not think about "a list of car data" and "a function for braking" separately. You think about the car.

You have already used objects. A list is an object: it has data (its items) and actions (append, sort, pop). A text is an object too: "hello".upper().

OOP stands on four ideas. This part explains each one in plain words. The code comes later.

1.2Encapsulation: keep things together, and protect them

Encapsulation means two things:

  1. The data and the actions that work on it are kept together in one place (one "capsule").
  2. The data is protected: it can be changed only in the allowed ways.

Real-life examples

  • A bank account. You cannot open the bank's database and type a new balance. You can only deposit and withdraw, and the bank checks every operation (you cannot withdraw more than you have).
  • A medicine capsule. The ingredients are packed inside one shell. You take the capsule, not the separate powders.
  • A car's engine under the hood. You change the speed with the pedals, not by touching the engine with your hands.

Why it helps: the data cannot get into a wrong state (a negative balance, an age of -5), because every change goes through a method that checks it.

1.3Abstraction: show what it does, hide how it does it

Abstraction means showing only the simple controls that a user needs, and hiding the complicated details.

Real-life examples

  • Driving a car. You use the steering wheel, the pedals and the gear stick. You do not need to know how the engine burns fuel.
  • A coffee machine. You press one button, "Coffee". Inside, the machine heats water, grinds beans and pumps water. You see none of it.
  • A TV remote. One button changes the channel. The electronics behind it are hidden.

Why it helps: you can use something without understanding its inside, and the inside can be changed later without changing how you use it.

1.4Encapsulation and abstraction are not the same

They are close, and beginners often mix them up:

Encapsulation and abstraction are not the same
EncapsulationAbstraction
QuestionHow is the data kept safe?What does the user need to see?
Ideapack data and methods together, and protect the datahide the complicated steps behind a simple action
Bank accountthe balance can be changed only by deposit and withdrawyou press "Withdraw", and do not see how the bank records it

1.5Inheritance: build on what already exists

Inheritance means creating a new kind of thing from an existing one. The new one gets everything the old one has, and can add its own things or change some.

Real-life examples

  • Children and parents. A child inherits features from the parents (eye color, height) and also has features of their own.
  • Vehicles. A car, a bus and a truck are all vehicles: each has wheels and an engine, and each can drive. A bus adds passenger seats, a truck adds a cargo area.
  • People at a school. A student and a teacher are both persons: each has a name and an age. A student also has grades, a teacher also has a subject.

The existing kind is called the parent (or base) class. The new kind is the child class. The test is the words "is a": a dog is an animal, a student is a person.

Why it helps: you write the shared parts once, in the parent, and do not repeat them in every child.

1.6Polymorphism: one name, many forms

Polymorphism means that the same action works on different kinds of things, and each kind does it in its own way. The word means "many forms".

Real-life examples

  • "Speak!" Say it to a dog and it barks. Say it to a cat and it meows. The command is the same, the result depends on who receives it.
  • The "play" button. On a music app it plays a song, on a video app it plays a film. One button, different behaviour.
  • "Draw yourself." A circle draws a round shape, a square draws four sides. The request is the same.

Why it helps: you can treat different objects in the same way (for example in one loop) without asking each time "which kind are you?".

1.7The four ideas in one table

The four ideas in one table
IdeaIn one sentenceReal-life example
Encapsulationkeep data and its actions together, and protect the dataa bank account: only deposit and withdraw can change the balance
Abstractionshow the simple controls, hide the detailsa coffee machine: one button, many hidden steps
Inheritancemake a new kind from an existing kinda bus is a vehicle with passenger seats
Polymorphismone action, done differently by each kind"speak": a dog barks, a cat meows

Which of the four ideas is it?

1 of 8

An ATM gives you money only after it checks your balance. You cannot change the number yourself.

Try it yourself

You have used objects since the first lesson. Sort the list words with its own method and print it, print how many items it has, and print the text hello in capital letters with a method of the text.
Show a hint
words.sort() is a method of the list. len(words) counts. "hello".upper() is a method of the text.
Show the solution
Python
words = ["pear", "apple", "fig"]
words.sort()
print(words)
print(len(words))
print("hello".upper())

Output

['apple', 'fig', 'pear']
3
HELLO

2Classes, objects and methods

2.1Class and object

  • A class is a plan (a blueprint). It describes what data and what actions a kind of thing has.
  • An object is one real thing made from that plan.

Real-life picture: the plan of a house is the class. The houses built from it are the objects. One plan, many houses, and each house has its own color and its own owner.

Class and object
Class (the plan)Objects (real things)
DogRex, Bella, Max
StudentAylin, Murad
BankAccountAylin's account, Murad's account

The class: a plan

class Dog

attributes

name, age

methods

bark(), birthday()

An object

rex

name"Rex"

age3

An object

bella

name"Bella"

age5

The plan is written once. Every object made from it has the same attributes and methods, but its own values.

2.2The simplest class

Python
class Dog:
    pass

rex = Dog()
print(type(rex))

Output

<class '__main__.Dog'>

Change it and run: create a second object, bella = Dog(), and print its type.

  • class Dog: creates the class. Class names start with a capital letter.
  • Dog() creates an object from the class. The object is also called an instance.
  • pass means "nothing here yet".

2.3Attributes and __init__

To give every object its own data, we write a special method called __init__ (two underscores on each side). Python runs it automatically when an object is created:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
bella = Dog("Bella", 5)

print(rex.name, rex.age)
print(bella.name, bella.age)

Output

Rex 3
Bella 5

Change it and run: create a third dog with your own name and age, and print them.

  • self.name = name stores the value inside the object. name and age are the attributes of the object.
  • rex.name reads an attribute, with a dot.
  • Each object has its own values.

2.4What is self?

self is the object itself. When you write Dog("Rex", 3), Python creates a new, empty object and passes it to __init__ as the first parameter, self. You never pass it yourself.

What is self?
You writePython runs
rex = Dog("Rex", 3)__init__(rex, "Rex", 3)

Forgetting an argument gives an error:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex")

Error

TypeError: Dog.__init__() missing 1 required positional argument: 'age'

2.5Changing and adding attributes

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
rex.age = 4
print(rex.age)

Output

4

Change it and run: change the name too: rex.name = "Max".

An attribute that does not exist gives an AttributeError:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
print(rex.color)

Error

AttributeError: 'Dog' object has no attribute 'color'

2.6A method is a function inside a class

A method is an action the object can do. Its first parameter is always self, so it can use the object's own data:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(self.name, "says: Woof!")

    def birthday(self):
        self.age = self.age + 1

rex = Dog("Rex", 3)
rex.bark()
rex.birthday()
print(rex.age)

Output

Rex says: Woof!
4

Change it and run: call rex.birthday() three times. How old is Rex now?

  • rex.bark() calls the method. Python passes rex as self.
  • A method can read the attributes (bark) and change them (birthday).

2.7Methods with parameters and return values

Methods work like the functions you know. They can take more parameters and return a value:

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def scale(self, factor):
        self.width = self.width * factor
        self.height = self.height * factor

room = Rectangle(4, 3)
print(room.area())
room.scale(2)
print(room.width, room.height, room.area())

Output

12
8 6 48

Change it and run: add a method perimeter() and print it.

2.8Printing an object: __str__

Printing an object shows something unreadable:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
print(rex)

Output

<__main__.Dog object at 0x7f3a2c1b4d90>

Python shows the class name and the place of the object in memory (the numbers will be different on your computer).

The special method __str__ returns the text that print should show:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} ({self.age} years old)"

rex = Dog("Rex", 3)
print(rex)

Output

Rex (3 years old)

Change it and run: change the text that __str__ returns.

2.9Many objects in a list

Objects are values, so they can be stored in a list and used in a loop:

Python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def passed(self):
        return self.grade >= 50

students = [Student("Aylin", 85), Student("Murad", 42), Student("Leyla", 78)]

for student in students:
    if student.passed():
        print(student.name, "passed")
    else:
        print(student.name, "failed")

Output

Aylin passed
Murad failed
Leyla passed

Change it and run: add a fourth student to the list. The loop needs no change.

2.10An attribute shared by all objects

An attribute written directly in the class (not in __init__) belongs to the class and is shared by all its objects:

Python
class Dog:
    species = "dog"

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

rex = Dog("Rex")
bella = Dog("Bella")
print(rex.name, rex.species)
print(bella.name, bella.species)

Output

Rex dog
Bella dog

Change it and run: add a third dog. It has the species "dog" too.

An attribute shared by all objects
Instance attributeClass attribute
Writtenin __init__, as self.name = ...directly in the class
Belongs toone objectall objects of the class
Examplethe name of each dogthe species of all dogs

Try it yourself

Write a class Car with the attributes brand and year. Create two cars and print their attributes.
Show a hint
__init__(self, brand, year) stores both values with self.. The lines at the bottom create the two cars.
Show the solution
Python
class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

first = Car("Toyota", 2020)
second = Car("Kia", 2023)
print(first.brand, first.year)
print(second.brand, second.year)

Output

Toyota 2020
Kia 2023

3Encapsulation in Python

The idea again: keep the data and its methods together, and let the data change only in the allowed ways.

3.1The problem: data that anyone can break

Python
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

account = BankAccount("Aylin", 100)
account.balance = -5000
print(account.balance)

Output

-5000

Change it and run: set the balance to any value you like. Nothing stops you.

Nothing stops a wrong value. A negative balance makes no sense, but the object accepts it.

3.2The solution: change the data only through methods

Python
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self._balance = balance

    def deposit(self, amount):
        if amount <= 0:
            print("The amount must be positive")
            return
        self._balance = self._balance + amount

    def withdraw(self, amount):
        if amount > self._balance:
            print("Not enough money")
            return
        self._balance = self._balance - amount

    def get_balance(self):
        return self._balance

account = BankAccount("Aylin", 100)
account.deposit(50)
account.withdraw(500)
account.deposit(-20)
print(account.get_balance())

Output

Not enough money
The amount must be positive
150

Change it and run: deposit 1000, then withdraw 200, and print the balance.

  • The balance is stored in _balance. The underscore at the start is a message to other programmers: "this is internal, do not touch it directly".
  • deposit and withdraw are the only allowed ways to change it, and they check every change.
  • get_balance lets others read the value.

This is the bank account from Part 1: you cannot type a new balance, you can only deposit and withdraw.

The balance can change only through the methods. Try them.

_balance

100

account = BankAccount("Aylin", 100)

The account starts with 100.

3.3How strong is the protection?

How strong is the protection?
NameMeaningCan it be reached from outside?
balancepublic: anyone may use ityes
_balanceinternal: please do not touchyes, but you should not
__balanceprivate: Python hides the namenot by this name

One underscore is only an agreement. Two underscores make Python hide the name:

Python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

account = BankAccount(100)
print(account.get_balance())
print(account.__balance)

Output

100

Error

AttributeError: 'BankAccount' object has no attribute '__balance'. Did you mean: 'get_balance'?

In most Python programs, one underscore is enough.

3.4Raising an error instead of printing

In the last lesson we learned that a function should raise an error when a value is not acceptable. The same is true for methods:

Python
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self._balance = balance

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("Not enough money")
        self._balance = self._balance - amount

account = BankAccount("Aylin", 100)
try:
    account.withdraw(500)
except ValueError as error:
    print("Problem:", error)

Output

Problem: Not enough money

Change it and run: withdraw 60 instead of 500. No error is raised.

Try it yourself

Write a class Battery. It starts at level 50, kept in _level. charge(amount) adds to the level but never above 100, and raises a ValueError with the message the amount must be positive for an amount of 0 or less. get_level() returns the level.
Show a hint
In charge, check the amount first and raise. Then self._level = min(100, self._level + amount) keeps the level at 100 or below.
Show the solution
Python
class Battery:
    def __init__(self):
        self._level = 50

    def charge(self, amount):
        if amount <= 0:
            raise ValueError("the amount must be positive")
        self._level = min(100, self._level + amount)

    def get_level(self):
        return self._level

battery = Battery()
battery.charge(30)
print(battery.get_level())
battery.charge(70)
print(battery.get_level())
try:
    battery.charge(-10)
except ValueError as error:
    print(error)

Output

80
100
the amount must be positive

4Abstraction in Python

The idea again: show a simple action, hide the steps behind it.

4.1One simple method, several hidden steps

Python
class CoffeeMachine:
    def _heat_water(self):
        print("  heating the water")

    def _grind_beans(self):
        print("  grinding the beans")

    def _pour(self):
        print("  pouring the coffee")

    def make_coffee(self):
        print("Making coffee:")
        self._heat_water()
        self._grind_beans()
        self._pour()
        print("Your coffee is ready")

machine = CoffeeMachine()
machine.make_coffee()

Output

Making coffee:
  heating the water
  grinding the beans
  pouring the coffee
Your coffee is ready

Change it and run: add a fourth hidden step, _add_milk, and call it inside make_coffee.

The user of the class needs to know one method: make_coffee(). The three steps start with an underscore, because they are internal details. This is the coffee machine from Part 1: one button.

4.2You use abstraction every day

When you write numbers.sort(), you do not know (and do not need to know) how Python sorts the list. You only know what it does. That is abstraction.

Python
numbers = [40, 10, 30]
numbers.sort()
print(numbers)
print(len("hello"))

Output

[10, 30, 40]
5

4.3The inside can change, the outside stays the same

Python
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    def in_fahrenheit(self):
        return self._celsius * 9 / 5 + 32

today = Temperature(25)
print(today.in_fahrenheit())

Output

77.0

Change it and run: create a second object for 0 degrees.

If the class later stores the temperature in another way, every program that calls in_fahrenheit() still works. Users depend on the method, not on the details.

Try it yourself

Write a class Laundry with two hidden steps, _wash() (prints washing) and _dry() (prints drying), and one public method run() that calls both and then prints Done.
Show a hint
Three methods. Inside run, call the hidden ones with self.: self._wash().
Show the solution
Python
class Laundry:
    def _wash(self):
        print("washing")

    def _dry(self):
        print("drying")

    def run(self):
        self._wash()
        self._dry()
        print("Done")

Laundry().run()

Output

washing
drying
Done

5Inheritance in Python

The idea again: make a new class from an existing one. The child gets everything the parent has.

5.1A parent and a child

Python
class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(self.name, "is eating")

class Dog(Animal):
    def bark(self):
        print(self.name, "says: Woof!")

rex = Dog("Rex")
rex.eat()
rex.bark()

Output

Rex is eating
Rex says: Woof!

Change it and run: add a class Cat(Animal) with a method meow.

  • class Dog(Animal): means: Dog is a child of Animal.
  • Dog has no __init__ and no eat, but both work: they are inherited from Animal.
  • bark is new: only dogs have it.

Animal

has

name, eat()

a dog is an animal, a cat is an animal

Dog(Animal)

inherited from Animal

name, eat()

adds

bark()

Cat(Animal)

inherited from Animal

name, eat()

adds

meow()

The shared parts are written once, in the parent. Each child gets them for free and adds only what is new.

5.2Adding attributes in the child: super()

When the child needs its own __init__, it calls the parent's __init__ first with super():

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

    def introduce(self):
        print("I am", self.name)

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

aylin = Student("Aylin", 20, 85)
aylin.introduce()
print(aylin.name, aylin.age, aylin.grade)

Output

I am Aylin
Aylin 20 85

Change it and run: add a method passed() to Student that returns self.grade >= 50.

super().__init__(name, age) lets Person store the name and the age. Then Student adds the grade. Nothing is written twice.

5.3Changing a method in the child: overriding

If the child defines a method with the same name as the parent's, the child's version is used. This is called overriding:

Python
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(self.name, "makes a sound")

class Dog(Animal):
    def speak(self):
        print(self.name, "says: Woof!")

class Fish(Animal):
    pass

Dog("Rex").speak()
Fish("Nemo").speak()

Output

Rex says: Woof!
Nemo makes a sound

Change it and run: give Fish its own speak method.

Dog has its own speak. Fish has none, so it uses the parent's.

5.4"Is a": isinstance

Python
class Animal:
    pass

class Dog(Animal):
    pass

rex = Dog()
print(isinstance(rex, Dog))
print(isinstance(rex, Animal))
print(isinstance(rex, str))

Output

True
True
False

Change it and run: create cat = Animal() and check isinstance(cat, Dog).

A dog is a dog, and a dog is an animal.

"Is a": isinstance
WordMeaningIn the examples
Parent (base) classthe existing classAnimal, Person
Child classthe new class built on itDog, Student
Inheritget the attributes and methods of the parentrex.eat()
super()the parent, used to call its methodssuper().__init__(name, age)
Overridereplace a parent's method in the childDog.speak

Try it yourself

Write a class Vehicle with a brand and a method describe() that returns This is a and the brand. Then write a child class Car that also has a number of doors. Use super().__init__.
Show a hint
describe returns "This is a " + self.brand. Car.__init__(self, brand, doors) calls super().__init__(brand) and then stores the doors.
Show the solution
Python
class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def describe(self):
        return "This is a " + self.brand

class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand)
        self.doors = doors

car = Car("Kia", 4)
print(car.describe())
print(car.doors)
print(isinstance(car, Vehicle))

Output

This is a Kia
4
True

6Polymorphism in Python

The idea again: the same method name, and each kind of object does it in its own way.

6.1One loop, different objects

Python
class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class Cow:
    def speak(self):
        return "Moo!"

animals = [Dog(), Cat(), Cow()]
for animal in animals:
    print(animal.speak())

Output

Woof!
Meow!
Moo!

Change it and run: add a class Duck with speak and put a duck into the list.

The loop does not ask "are you a dog or a cat?". It calls speak(), and every object answers in its own way. This is "Speak!" from Part 1.

6.2Polymorphism with inheritance

Often the classes share a parent, and each child overrides the same method:

Python
class Shape:
    def __init__(self, name):
        self.name = name

    def area(self):
        return 0

class Rectangle(Shape):
    def __init__(self, width, height):
        super().__init__("rectangle")
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        super().__init__("circle")
        self.radius = radius

    def area(self):
        return round(3.14159 * self.radius ** 2, 2)

shapes = [Rectangle(4, 3), Circle(2), Rectangle(5, 5)]
for shape in shapes:
    print(shape.name, shape.area())

print("Total:", sum(shape.area() for shape in shapes))

Output

rectangle 12
circle 12.57
rectangle 25
Total: 49.57

Change it and run: add a class Triangle(Shape) with a base and a height, and put one into the list.

Adding a new shape later (a triangle) needs no change in the loop. That is the power of polymorphism.

6.3Without polymorphism

The same program without it needs an if for every kind, and every new kind means changing this code:

Python
shapes = [("rectangle", 4, 3), ("circle", 2, 0)]
for kind, a, b in shapes:
    if kind == "rectangle":
        print(kind, a * b)
    elif kind == "circle":
        print(kind, round(3.14159 * a ** 2, 2))

Output

rectangle 12
circle 12.57

6.4Python's own polymorphism

You have used it since the first lesson. len() and + work on different types, and each type does it in its own way:

Python
print(len("hello"))
print(len([1, 2, 3]))
print(len({"a": 1, "b": 2}))

print(2 + 3)
print("2" + "3")
print([2] + [3])

Output

5
3
2
5
23
[2, 3]

6.5The four ideas together

The four ideas together
IdeaIn plain wordsIn Python
Encapsulationkeep data and methods together, protect the dataa class, self._balance, methods that check
Abstractiona simple method hides the stepsmake_coffee() calls _heat_water(), _grind_beans(), _pour()
Inheritancea child class gets everything from its parentclass Dog(Animal):, super().__init__(...)
Polymorphismthe same method name, a different result per classfor shape in shapes: shape.area()

One small program with all four:

Python
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self._salary = salary

    def pay(self):
        return self._salary

    def describe(self):
        return f"{self.name} earns {self.pay()}"

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self._bonus = bonus

    def pay(self):
        return self._salary + self._bonus

staff = [Employee("Aylin", 1000), Manager("Murad", 1500, 400)]
for person in staff:
    print(person.describe())

Output

Aylin earns 1000
Murad earns 1900

Change it and run: add a third person, Manager("Leyla", 2000, 0).

  • Encapsulation: the salary is kept inside the object, as _salary.
  • Abstraction: describe() gives a ready sentence. The caller does not calculate anything.
  • Inheritance: Manager is an Employee and reuses its __init__ and describe.
  • Polymorphism: pay() gives a different result for a manager, and describe() uses the right one.

6.6When should I write a class?

  • Use a class when several pieces of data belong together and there are actions on them (an account, a student, a product).
  • A dictionary is enough for simple data without actions.
  • A function is enough for one calculation.

Try it yourself

Write a class Animal with a method speak() that returns "...", and two child classes Dog and Cat that override it (Woof! and Meow!). Call speak() for each animal in a list.
Show a hint
Each child defines its own speak(self) with the same name. The loop at the bottom is already written.
Show the solution
Python
class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

for animal in [Animal(), Dog(), Cat()]:
    print(animal.speak())

Output

...
Woof!
Meow!

7Modules and packages

7.1What is a module?

A module is a file with Python code (functions, classes, values) that you can use in another program. Python comes with many ready modules. This collection is called the standard library.

Real-life picture: a toolbox. You do not make a hammer each time you need one. You open the toolbox and take it.

7.2import

Python
import math

print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7), math.ceil(3.2))

Output

4.0
3.141592653589793
3 4

Change it and run: print math.sqrt(2) and math.pow(2, 10).

import math loads the module. Its functions are used with the module name and a dot: math.sqrt.

7.3from ... import

Import only the names you need, and use them without the module name:

Python
from math import sqrt, pi

print(sqrt(25))
print(round(pi, 2))

Output

5.0
3.14

Change it and run: import floor too and print floor(9.99).

7.4as: a shorter name

Python
import statistics as stats

grades = [85, 92, 78, 60]
print(stats.mean(grades))
print(stats.median(grades))

Output

78.75
81.5

Change it and run: add the grade 100 to the list.

as: a shorter name
FormHow you use itGood for
import mathmath.sqrt(16)the usual way: it is clear where sqrt comes from
from math import sqrtsqrt(16)one or two names that you use often
import statistics as statsstats.mean(...)long module names
from math import *sqrt(16)avoid it: you no longer see where a name comes from

7.5Some useful modules of the standard library

Some useful modules of the standard library
ModuleWhat it givesExample
mathmathematical functionsmath.sqrt(16)
randomrandom numbers and choicesrandom.randint(1, 6)
statisticsmean, median and morestatistics.mean([1, 2, 3])
datetimedates and timesdatetime.date(2026, 10, 3)
Python
import datetime

day = datetime.date(2026, 10, 3)
print(day)
print(day.year, day.month, day.day)
print(day.strftime("%d.%m.%Y"))

Output

2026-10-03
2026 10 3
03.10.2026

Change it and run: use your own date of birth.

random gives a different result each time, so its output is not shown here:

Python
import random

print(random.randint(1, 6))
print(random.choice(["red", "green", "blue"]))

Notice that datetime.date(2026, 10, 3) creates an object of the class date, and day.year is an attribute. Modules are full of classes.

7.6A module that does not exist

Python
import maths

Error

ModuleNotFoundError: No module named 'maths'

7.7Your own module

Any .py file is a module. Suppose you save this as shapes.py:

Python
# shapes.py
def rectangle_area(width, height):
    return width * height

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

Another file in the same folder can use it:

Python
# main.py
import shapes

print(shapes.rectangle_area(4, 3))
circle = shapes.Circle(2)
print(circle.area())

This is how big programs are organised: related functions and classes live in their own module.

7.8Packages

A package is a folder of modules. Big libraries are packages.

school/
    students.py
    grades.py
    reports.py
Python
from school import grades
from school.students import Student

7.9Packages made by other people

Thousands of packages are not part of Python itself. You install them once, and then import them like any module. In a terminal or in Anaconda Prompt:

pip install numpy

or, with Anaconda:

conda install numpy

Then in your program:

Python
import numpy as np
import pandas as pd

np and pd are the short names everybody uses. The rest of this course is built on such packages: NumPy, pandas, Matplotlib and scikit-learn.

Packages made by other people
WordMeaningExample
Moduleone .py filemath, your shapes.py
Packagea folder of modulesnumpy, pandas
Standard librarythe modules that come with Pythonmath, random, datetime
pip / condatools that install packagespip install numpy

Try it yourself

Use the math module to print the square root of 81 and the value of pi rounded to 3 decimal places.
Show a hint
math.sqrt(81) and round(math.pi, 3).
Show the solution
Python
import math

print(math.sqrt(81))
print(round(math.pi, 3))

Output

9.0
3.142

8Common mistakes

The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.

Forgetting self in a method definition

Wrong

class Dog:
    def bark():
        print("Woof!")

rex = Dog()
rex.bark()
TypeError: Dog.bark() takes 0 positional arguments but 1 was given

Right

class Dog:
    def bark(self):
        print("Woof!")

rex = Dog()
rex.bark()

# prints: Woof!

TypeError when the method is called. The first parameter of every method is self.

Forgetting self. when using an attribute

Wrong

class Dog:
    def __init__(self, name):
        name = name

rex = Dog("Rex")
print(rex.name)
AttributeError: 'Dog' object has no attribute 'name'

Right

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

rex = Dog("Rex")
print(rex.name)

# prints: Rex

NameError, or the value is lost. Write self.name, not name.

Writing __init__ with one underscore, or init

Wrong

class Dog:
    def init(self, name):
        self.name = name

rex = Dog("Rex")
TypeError: Dog() takes no arguments

Right

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

rex = Dog("Rex")
print(rex.name)

# prints: Rex

The method is never run. Two underscores on each side.

Forgetting the parentheses when creating an object

Wrong

class Dog:
    pass

rex = Dog
print(type(rex))

# prints: <class 'type'>

Right

class Dog:
    pass

rex = Dog()
print(type(rex))

# prints: <class '__main__.Dog'>

You get the class, not an object. Write rex = Dog().

Forgetting an argument of __init__

Wrong

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex")
TypeError: Dog.__init__() missing 1 required positional argument: 'age'

Right

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
bella = Dog("Bella", 5)

print(rex.name, rex.age)
print(bella.name, bella.age)

# prints: Rex 3, Bella 5

TypeError. Pass every argument.

Forgetting super().__init__(...) in a child

Wrong

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

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

aylin = Student("Aylin", 85)
print(aylin.name)
AttributeError: 'Student' object has no attribute 'name'

Right

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

    def introduce(self):
        print("I am", self.name)

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

aylin = Student("Aylin", 20, 85)
aylin.introduce()
print(aylin.name, aylin.age, aylin.grade)

# prints: I am Aylin, Aylin 20 85

The parent's attributes do not exist. Call it first in the child's __init__.

Changing protected data directly

Wrong

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

account = BankAccount("Aylin", 100)
account.balance = -5000
print(account.balance)

# prints: -5000

Right

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self._balance = balance

    def deposit(self, amount):
        if amount <= 0:
            print("The amount must be positive")
            return
        self._balance = self._balance + amount

    def withdraw(self, amount):
        if amount > self._balance:
            print("Not enough money")
            return
        self._balance = self._balance - amount

    def get_balance(self):
        return self._balance

account = BankAccount("Aylin", 100)
account.deposit(50)
account.withdraw(500)
account.deposit(-20)
print(account.get_balance())

# prints: Not enough money, The amount must be positive, 150

Wrong values (a negative balance). Use the methods.

Using a method without parentheses

Wrong

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

room = Rectangle(4, 3)
print(room.area == 12)

# prints: False

Right

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

room = Rectangle(4, 3)
print(room.area() == 12)

# prints: True

You get the method, not its result. Write room.area().

A wrong module name

Wrong

import maths
ModuleNotFoundError: No module named 'maths'

Right

import math

print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7), math.ceil(3.2))

# prints: 4.0, 3.141592653589793, 3 4

ModuleNotFoundError. Check the spelling, or install the package.

Forgetting self in a method definition:

Python
class Dog:
    def bark():
        print("Woof!")

rex = Dog()
rex.bark()

Error

TypeError: Dog.bark() takes 0 positional arguments but 1 was given

Python passes the object as the first argument, but bark has no parameter to receive it.

Forgetting self. when storing an attribute:

Python
class Dog:
    def __init__(self, name):
        name = name

rex = Dog("Rex")
print(rex.name)

Error

AttributeError: 'Dog' object has no attribute 'name'

Forgetting super().__init__(...):

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

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

aylin = Student("Aylin", 85)
print(aylin.name)

Error

AttributeError: 'Student' object has no attribute 'name'

9Solved problems (easy to medium-hard)

Every example was run, and the outputs are real.

9.1Level 1: Easy

Problem 1: A class with two attributes

Python
class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

book = Book("Python Basics", 320)
print(book.title)
print(book.pages)

Output

Python Basics
320

Problem 2: A method that uses the attributes

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

room = Rectangle(5, 3)
print(room.area())
print(room.perimeter())

Output

15
16

Change it and run: create a square room, 4 by 4.

Problem 3: A method that changes the object

Python
class Counter:
    def __init__(self):
        self.value = 0

    def increase(self):
        self.value = self.value + 1

counter = Counter()
counter.increase()
counter.increase()
counter.increase()
print(counter.value)

Output

3

Change it and run: call increase() two more times.

Why: the object remembers its value between the calls. A plain function cannot do that.

Problem 4: Printing an object

Python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name}: {self.price} AZN"

print(Product("Notebook", 4.5))
print(Product("Pen", 1.2))

Output

Notebook: 4.5 AZN
Pen: 1.2 AZN

Problem 5: Using a module

Python
import math

radius = 3
print(round(math.pi * radius ** 2, 2))
print(math.sqrt(144))
print(math.factorial(5))

Output

28.27
12.0
120

9.2Level 2: Medium

Problem 6: A protected age (encapsulation)

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self._age = 0
        self.set_age(age)

    def set_age(self, age):
        if age < 0 or age > 120:
            raise ValueError("age must be between 0 and 120")
        self._age = age

    def get_age(self):
        return self._age

aylin = Person("Aylin", 20)
print(aylin.get_age())
try:
    aylin.set_age(-5)
except ValueError as error:
    print("Problem:", error)
print(aylin.get_age())

Output

20
Problem: age must be between 0 and 120
20

Change it and run: try aylin.set_age(200).

Why: every change of the age goes through set_age, which checks it. The wrong value never reaches the object.

Problem 7: A simple method that hides the steps (abstraction)

Python
class Report:
    def __init__(self, grades):
        self._grades = grades

    def _average(self):
        return sum(self._grades) / len(self._grades)

    def _best(self):
        return max(self._grades)

    def summary(self):
        return f"Average: {self._average()}, best: {self._best()}"

report = Report([85, 92, 78, 65])
print(report.summary())

Output

Average: 80.0, best: 92

Why: the user calls one method, summary(). How the average and the best grade are found is an internal detail.

Problem 8: A child class (inheritance)

Python
class Vehicle:
    def __init__(self, brand, wheels):
        self.brand = brand
        self.wheels = wheels

    def describe(self):
        return f"{self.brand} with {self.wheels} wheels"

class Bus(Vehicle):
    def __init__(self, brand, seats):
        super().__init__(brand, 6)
        self.seats = seats

bus = Bus("Isuzu", 40)
print(bus.describe())
print(bus.seats)

Output

Isuzu with 6 wheels
40

Change it and run: print bus.wheels.

Why: a bus is a vehicle. describe is written once, in Vehicle.

Problem 9: The same method in different classes (polymorphism)

Python
class Email:
    def send(self, text):
        return f"Email: {text}"

class Sms:
    def send(self, text):
        return f"SMS: {text[:10]}"

for channel in [Email(), Sms()]:
    print(channel.send("Your lesson starts at 19:00"))

Output

Email: Your lesson starts at 19:00
SMS: Your lesso

Problem 10: Objects in a list

Python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

students = [Student("Aylin", 85), Student("Murad", 42), Student("Leyla", 78)]

best = max(students, key=lambda student: student.grade)
passed = [student.name for student in students if student.grade >= 50]
average = sum(student.grade for student in students) / len(students)

print("Best:", best.name)
print("Passed:", passed)
print("Average:", round(average, 1))

Output

Best: Aylin
Passed: ['Aylin', 'Leyla']
Average: 68.3

9.3Level 3: Medium-Hard

Problem 11: A bank account with a history

Python
class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        self._balance = 0
        self._history = []

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("the amount must be positive")
        self._balance = self._balance + amount
        self._history.append(f"+{amount}")

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("not enough money")
        self._balance = self._balance - amount
        self._history.append(f"-{amount}")

    def __str__(self):
        return f"{self.owner}: {self._balance} ({', '.join(self._history)})"

account = BankAccount("Aylin")
account.deposit(100)
account.withdraw(30)
try:
    account.withdraw(500)
except ValueError as error:
    print("Problem:", error)
print(account)

Output

Problem: not enough money
Aylin: 70 (+100, -30)

Change it and run: deposit a negative amount inside the try.

Problem 12: Employees and managers

Python
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self._salary = salary

    def pay(self):
        return self._salary

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self._bonus = bonus

    def pay(self):
        return super().pay() + self._bonus

staff = [Employee("Aylin", 1000), Manager("Murad", 1500, 400), Employee("Leyla", 1200)]
for person in staff:
    print(person.name, person.pay())
print("Total:", sum(person.pay() for person in staff))

Output

Aylin 1000
Murad 1900
Leyla 1200
Total: 4100

Change it and run: add Manager("Kamran", 1800, 250) to the staff.

Why: super().pay() reuses the parent's calculation, and the manager adds the bonus. The loop treats everyone the same way.

Problem 13: A shopping cart made of objects

Python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

class Cart:
    def __init__(self):
        self._items = []

    def add(self, product, amount):
        self._items.append((product, amount))

    def total(self):
        return sum(product.price * amount for product, amount in self._items)

    def show(self):
        for product, amount in self._items:
            print(product.name, "x", amount)
        print("Total:", self.total())

cart = Cart()
cart.add(Product("Notebook", 4.5), 2)
cart.add(Product("Pen", 1.2), 5)
cart.show()

Output

Notebook x 2
Pen x 5
Total: 15.0

Change it and run: add a third product to the cart.

Why: one object can hold other objects. The cart keeps its list of items inside and offers three simple methods.

Problem 14: Shapes with a common parent

Python
import math

class Shape:
    def area(self):
        raise NotImplementedError("each shape must define area()")

    def describe(self):
        return f"{type(self).__name__} with area {round(self.area(), 2)}"

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

for shape in [Square(3), Circle(1), Square(1.5)]:
    print(shape.describe())

Output

Square with area 9
Circle with area 3.14
Square with area 2.25

Change it and run: add a class Rectangle(Shape) and put one into the list.

Why: describe is written once in the parent and calls area(), which each child defines in its own way. The parent's area raises an error, so a child cannot forget to write its own.

Problem 15: A small library system

Python
class Book:
    def __init__(self, title):
        self.title = title
        self.available = True

class Library:
    def __init__(self):
        self._books = {}

    def add(self, title):
        self._books[title] = Book(title)

    def borrow(self, title):
        if title not in self._books:
            raise KeyError(title)
        book = self._books[title]
        if not book.available:
            raise ValueError(f"{title} is already borrowed")
        book.available = False

    def available_titles(self):
        return [title for title, book in self._books.items() if book.available]

library = Library()
library.add("Python Basics")
library.add("Data Science 101")
library.borrow("Python Basics")

try:
    library.borrow("Python Basics")
except ValueError as error:
    print("Problem:", error)

print(library.available_titles())

Output

Problem: Python Basics is already borrowed
['Data Science 101']

Change it and run: try to borrow "Statistics", a book the library does not have, and catch the KeyError.

10Practice problems (try them yourself)

Fifteen problems in three levels. You write the class above the lines that are already in the editor: they create objects of your class and print the results. Press Run to try, then Check.

Easy

One small class, or one module.

  1. 1.Write a class Circle with the attribute radius and a method area() that returns the area. Use math.pi.Examples: 1 gives 3.142 gives 12.570 gives 0.0
    Show a hint
    __init__(self, radius) stores the radius in self.radius. The area is math.pi * self.radius ** 2. Return it, do not print it.
    Show one possible solution
    Python
    import math
    
    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        def area(self):
            return math.pi * self.radius ** 2
    
    radius = float(input())
    circle = Circle(radius)
    print(round(circle.area(), 2))

    Output

    3.14
  2. 2.Write a class Counter with a method increase() and a method reset(). The counter starts at 0, in an attribute called value.
    Show a hint
    __init__(self) sets self.value = 0. increase adds 1 to self.value, and reset sets it back to 0.
    Show one possible solution
    Python
    class Counter:
        def __init__(self):
            self.value = 0
    
        def increase(self):
            self.value = self.value + 1
    
        def reset(self):
            self.value = 0
    
    counter = Counter()
    counter.increase()
    counter.increase()
    print(counter.value)
    counter.reset()
    print(counter.value)

    Output

    2
    0
  3. 3.Add a __str__ method to a class Student (name and grade), so that print(student) shows a text like Aylin: 85.Examples: Aylin 85 gives Aylin: 85Murad 42 gives Murad: 42Leyla 100 gives Leyla: 100
    Show a hint
    Write __init__(self, name, grade) first. __str__(self) must return the text: return f"{self.name}: {self.grade}".
    Show one possible solution
    Python
    class Student:
        def __init__(self, name, grade):
            self.name = name
            self.grade = grade
    
        def __str__(self):
            return f"{self.name}: {self.grade}"
    
    name, grade = input().split()
    student = Student(name, int(grade))
    print(student)

    Output

    Aylin: 85
  4. 4.Use the statistics module to print the mean and the median of [4, 8, 15, 16, 23, 42], each on its own line.
    Show a hint
    The functions are statistics.mean(numbers) and statistics.median(numbers).
    Show one possible solution
    Python
    import statistics
    
    numbers = [4, 8, 15, 16, 23, 42]
    print(statistics.mean(numbers))
    print(statistics.median(numbers))

    Output

    18
    15.5

Medium

Methods that change the object, and a first child class.

  1. 5.Write a class Temperature that stores degrees Celsius and has a method to_fahrenheit(). The formula is F = C × 9 / 5 + 32.Examples: 25 gives 77.00 gives 32.0100 gives 212.0
    Show a hint
    Store the value in __init__. The method returns self.celsius * 9 / 5 + 32.
    Show one possible solution
    Python
    class Temperature:
        def __init__(self, celsius):
            self.celsius = celsius
    
        def to_fahrenheit(self):
            return self.celsius * 9 / 5 + 32
    
    celsius = float(input())
    print(round(Temperature(celsius).to_fahrenheit(), 1))

    Output

    77.0
  2. 6.Write a class BankAccount with deposit and withdraw. A withdrawal larger than the balance must print not enough money and leave the balance unchanged. The class takes the starting balance and keeps it in an attribute called balance.
    Show a hint
    In withdraw, check if amount > self.balance: first. Print the message and return, so the line that subtracts is not reached.
    Show one possible solution
    Python
    class BankAccount:
        def __init__(self, balance):
            self.balance = balance
    
        def deposit(self, amount):
            self.balance = self.balance + amount
    
        def withdraw(self, amount):
            if amount > self.balance:
                print("not enough money")
                return
            self.balance = self.balance - amount
    
    account = BankAccount(100)
    account.deposit(50)
    account.withdraw(500)
    account.withdraw(30)
    print(account.balance)

    Output

    not enough money
    120
  3. 7.Write a class Person (name) and a child class Teacher (name and subject). Use super().__init__. A method introduce() in Teacher returns a sentence with both values, like I am Aylin and I teach Python.Examples: Aylin Python gives I am Aylin and I teach PythonMurad SQL gives I am Murad and I teach SQLLeyla Statistics gives I am Leyla and I teach Statistics
    Show a hint
    class Teacher(Person):. In its __init__, call super().__init__(name) first, then store the subject. introduce returns an f-string.
    Show one possible solution
    Python
    class Person:
        def __init__(self, name):
            self.name = name
    
    class Teacher(Person):
        def __init__(self, name, subject):
            super().__init__(name)
            self.subject = subject
    
        def introduce(self):
            return f"I am {self.name} and I teach {self.subject}"
    
    name, subject = input().split()
    teacher = Teacher(name, subject)
    print(teacher.introduce())

    Output

    I am Aylin and I teach Python
  4. 8.Write a class Rectangle with area() and a child class Square that takes only one side.Examples: 4 gives 16 True1 gives 1 True0 gives 0 True
    Show a hint
    A square is a rectangle with equal sides. Square.__init__(self, side) needs one line: super().__init__(side, side). area is inherited.
    Show one possible solution
    Python
    class Rectangle:
        def __init__(self, width, height):
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
    class Square(Rectangle):
        def __init__(self, side):
            super().__init__(side, side)
    
    side = int(input())
    square = Square(side)
    print(square.area(), isinstance(square, Rectangle))

    Output

    16 True
  5. 9.Write a class ShoppingList that keeps its items in an internal list and has the methods add(item), remove(item) and count().
    Show a hint
    __init__ creates self._items = []. The three methods use the list methods you know: append, remove and len.
    Show one possible solution
    Python
    class ShoppingList:
        def __init__(self):
            self._items = []
    
        def add(self, item):
            self._items.append(item)
    
        def remove(self, item):
            self._items.remove(item)
    
        def count(self):
            return len(self._items)
    
    shopping = ShoppingList()
    shopping.add("milk")
    shopping.add("bread")
    shopping.add("eggs")
    shopping.remove("bread")
    print(shopping.count())

    Output

    2

Medium-Hard

Protected data, several classes, and errors raised by methods.

  1. 10.Write a class Student with a name and an internal list of grades. Methods: add_grade(grade) (it raises a ValueError if the grade is not from 0 to 100), average() and best().Examples: 85 92 78 gives 85.0 92 0100 150 50 gives 75.0 100 160 gives 60.0 60 0
    Show a hint
    __init__(self, name) creates self._grades = []. In add_grade, check the range first and raise ValueError(...), then append. average uses sum and len, best uses max.
    Show one possible solution
    Python
    class Student:
        def __init__(self, name):
            self.name = name
            self._grades = []
    
        def add_grade(self, grade):
            if grade < 0 or grade > 100:
                raise ValueError("the grade must be from 0 to 100")
            self._grades.append(grade)
    
        def average(self):
            return sum(self._grades) / len(self._grades)
    
        def best(self):
            return max(self._grades)
    
    student = Student("Aylin")
    rejected = 0
    for text in input().split():
        try:
            student.add_grade(int(text))
        except ValueError:
            rejected = rejected + 1
    print(student.average(), student.best(), rejected)

    Output

    85.0 92 0
  2. 11.Write classes Shape, Rectangle, Circle and Triangle, each with area(). Put several shapes in a list and print the name of the shape with the largest area. Each shape has an attribute name: "rectangle", "circle" or "triangle". A triangle takes a base and a height.
    Show a hint
    The parent Shape stores the name. Each child calls super().__init__("rectangle") with its own name and defines area(). The area of a triangle is base × height / 2.
    Show one possible solution
    Python
    import math
    
    class Shape:
        def __init__(self, name):
            self.name = name
    
        def area(self):
            return 0
    
    class Rectangle(Shape):
        def __init__(self, width, height):
            super().__init__("rectangle")
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
    class Circle(Shape):
        def __init__(self, radius):
            super().__init__("circle")
            self.radius = radius
    
        def area(self):
            return math.pi * self.radius ** 2
    
    class Triangle(Shape):
        def __init__(self, base, height):
            super().__init__("triangle")
            self.base = base
            self.height = height
    
        def area(self):
            return self.base * self.height / 2
    
    shapes = [Rectangle(4, 3), Circle(2), Triangle(6, 5)]
    largest = max(shapes, key=lambda shape: shape.area())
    print(largest.name)

    Output

    triangle
  3. 12.Write a class Employee with pay(), and child classes Manager (salary plus bonus) and Intern (half of the salary). Print the total pay of a list of staff.
    Show a hint
    Employee stores the name and the salary, and pay() returns the salary. Manager adds a bonus in its own __init__ (with super().__init__) and overrides pay. Intern only overrides pay.
    Show one possible solution
    Python
    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self._salary = salary
    
        def pay(self):
            return self._salary
    
    class Manager(Employee):
        def __init__(self, name, salary, bonus):
            super().__init__(name, salary)
            self._bonus = bonus
    
        def pay(self):
            return self._salary + self._bonus
    
    class Intern(Employee):
        def pay(self):
            return self._salary / 2
    
    staff = [Employee("Aylin", 1000), Manager("Murad", 1500, 400), Intern("Leyla", 600)]
    print(sum(person.pay() for person in staff))

    Output

    3200.0
  4. 13.Write a class Stack with push(item), pop() and is_empty(). pop() on an empty stack raises an IndexError with your own message: the stack is empty.
    Show a hint
    Keep the items in self._items = []. push appends, pop removes and returns the last item. In pop, first check if self.is_empty(): and raise IndexError("the stack is empty").
    Show one possible solution
    Python
    class Stack:
        def __init__(self):
            self._items = []
    
        def push(self, item):
            self._items.append(item)
    
        def pop(self):
            if self.is_empty():
                raise IndexError("the stack is empty")
            return self._items.pop()
    
        def is_empty(self):
            return len(self._items) == 0
    
    stack = Stack()
    stack.push(1)
    stack.push(2)
    print(stack.pop())
    print(stack.is_empty())
    print(stack.pop())
    print(stack.is_empty())
    try:
        stack.pop()
    except IndexError as error:
        print(error)

    Output

    2
    False
    1
    True
    the stack is empty
  5. 14.Write a class Inventory that keeps products and their amounts in an internal dictionary. Methods: add(name, amount), remove(name, amount) (it raises a ValueError if there is not enough), and report() that returns the names in alphabetical order. The error message is not enough and the name, like not enough notebook.
    Show a hint
    add uses the counting pattern: self._products[name] = self._products.get(name, 0) + amount. remove checks the amount first and raises. report returns sorted(self._products).
    Show one possible solution
    Python
    class Inventory:
        def __init__(self):
            self._products = {}
    
        def add(self, name, amount):
            self._products[name] = self._products.get(name, 0) + amount
    
        def remove(self, name, amount):
            if self._products.get(name, 0) < amount:
                raise ValueError("not enough " + name)
            self._products[name] = self._products[name] - amount
    
        def report(self):
            return sorted(self._products)
    
    inventory = Inventory()
    inventory.add("pen", 10)
    inventory.add("notebook", 5)
    inventory.add("pen", 5)
    inventory.remove("pen", 3)
    try:
        inventory.remove("notebook", 9)
    except ValueError as error:
        print(error)
    print(inventory.report())

    Output

    not enough notebook
    ['notebook', 'pen']
  6. 15.Write a class Clock with hours and minutes and a method tick() that adds one minute. After 23:59 comes 00:00. __str__ shows the time like 09:05.Examples: 9 4 gives 09:0523 59 gives 00:000 0 gives 00:01
    Show a hint
    In tick, add 1 to the minutes. If they reach 60, set them to 0 and add 1 to the hours. If the hours reach 24, set them to 0. Two digits with a leading zero: f"{self.hours:02}:{self.minutes:02}".
    Show one possible solution
    Python
    class Clock:
        def __init__(self, hours, minutes):
            self.hours = hours
            self.minutes = minutes
    
        def tick(self):
            self.minutes = self.minutes + 1
            if self.minutes == 60:
                self.minutes = 0
                self.hours = self.hours + 1
            if self.hours == 24:
                self.hours = 0
    
        def __str__(self):
            return f"{self.hours:02}:{self.minutes:02}"
    
    hours, minutes = map(int, input().split())
    clock = Clock(hours, minutes)
    clock.tick()
    print(clock)

    Output

    09:05

11Check yourself

Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.

Question 1

1.A bank account whose balance can be changed only by deposit and withdraw is an example of which idea?

Question 2

2.One button on a coffee machine hides heating, grinding and pouring. Which idea is this?

Question 3

3.What does this print?

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

rex = Dog("Rex")
bella = Dog("Bella")
rex.name = "Max"
print(rex.name, bella.name)

Question 4

4.What is self in a method?

Question 5

5.What happens when this runs?

class Dog:
    def bark():
        print("Woof")

Dog().bark()

Question 6

6.What does this print?

class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    pass

class Cat(Animal):
    def speak(self):
        return "Meow"

print(Dog().speak(), Cat().speak())

Question 7

7.What happens when this runs?

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

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

s = Student("Aylin", 85)
print(s.name)

Question 8

8.What does this print?

class A:
    pass

class B(A):
    pass

b = B()
print(isinstance(b, A), isinstance(b, B))

Question 9

9.What does this print?

class Cat:
    def speak(self):
        return "Meow"

class Cow:
    def speak(self):
        return "Moo"

for animal in [Cat(), Cow()]:
    print(animal.speak(), end=" ")

Question 10

10.After the line from math import sqrt, which line works?

Question 11

11.What does import numpy as np do?

Question 12

12.What does one underscore at the start of an attribute name, like _balance, mean?

0 of 12 answered.

12Quick summary

Quick summary
ConceptWhat it doesExample
Classthe plan for a kind of objectclass Dog:
Object (instance)one real thing made from a classrex = Dog("Rex", 3)
__init__runs when an object is createddef __init__(self, name):
selfthe object itselfself.name = name
Attributedata of an objectrex.name
Methodan action of an objectrex.bark()
__str__the text that print showsdef __str__(self):
Encapsulationdata and methods together, data protectedself._balance, deposit()
Abstractiona simple method hides the stepsmachine.make_coffee()
Inheritancea child class gets everything from its parentclass Dog(Animal):
super()calls a method of the parentsuper().__init__(name)
Polymorphismthe same method name, different behaviourfor s in shapes: s.area()
importloads a moduleimport math
from ... importloads chosen namesfrom math import sqrt
asgives a shorter nameimport numpy as np
Packagea folder of modules, often installed with pippip install numpy