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
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-07-oop-modules-packages.ipynb, 62 KB
Practice notebook
The 15 practice problems with a hint and a hidden solution for each.
topic-07-practice.ipynb, 33 KB
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.What OOP is, and the four ideas behind it, each with real-life examples
- 2.What a class and an object are, and how to write
__init__, attributes and methods - 3.Encapsulation: keeping data and the actions on it together, and protecting the data
- 4.Abstraction: hiding the details behind a simple method
- 5.Inheritance: building a new class on top of an existing one
- 6.Polymorphism: the same method name doing the right thing for each kind of object
- 7.Modules and packages:
import,from ... import,as, your own module, installing packages - 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:
- The data and the actions that work on it are kept together in one place (one "capsule").
- 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 | Abstraction | |
|---|---|---|
| Question | How is the data kept safe? | What does the user need to see? |
| Idea | pack data and methods together, and protect the data | hide the complicated steps behind a simple action |
| Bank account | the balance can be changed only by deposit and withdraw | you 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
| Idea | In one sentence | Real-life example |
|---|---|---|
| Encapsulation | keep data and its actions together, and protect the data | a bank account: only deposit and withdraw can change the balance |
| Abstraction | show the simple controls, hide the details | a coffee machine: one button, many hidden steps |
| Inheritance | make a new kind from an existing kind | a bus is a vehicle with passenger seats |
| Polymorphism | one 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
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
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 (the plan) | Objects (real things) |
|---|---|
Dog | Rex, Bella, Max |
Student | Aylin, Murad |
BankAccount | Aylin'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
2.2The simplest class
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.passmeans "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:
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 = namestores the value inside the object.nameandageare the attributes of the object.rex.namereads 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.
| You write | Python runs |
|---|---|
rex = Dog("Rex", 3) | __init__(rex, "Rex", 3) |
Forgetting an argument gives an error:
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
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:
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:
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 passesrexasself.- 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:
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:
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:
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:
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:
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.
| Instance attribute | Class attribute | |
|---|---|---|
| Written | in __init__, as self.name = ... | directly in the class |
| Belongs to | one object | all objects of the class |
| Example | the name of each dog | the species of all dogs |
Try it yourself
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
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
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
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". depositandwithdraware the only allowed ways to change it, and they check every change.get_balancelets 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?
| Name | Meaning | Can it be reached from outside? |
|---|---|---|
balance | public: anyone may use it | yes |
_balance | internal: please do not touch | yes, but you should not |
__balance | private: Python hides the name | not by this name |
One underscore is only an agreement. Two underscores make Python hide the name:
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:
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
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
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
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
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.
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
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
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
run, call the hidden ones with self.: self._wash().Show the solution
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
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:Dogis a child ofAnimal.Doghas no__init__and noeat, but both work: they are inherited fromAnimal.barkis 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()
5.2Adding attributes in the child: super()
When the child needs its own __init__, it calls the parent's __init__ first with super():
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:
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
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.
| Word | Meaning | In the examples |
|---|---|---|
| Parent (base) class | the existing class | Animal, Person |
| Child class | the new class built on it | Dog, Student |
| Inherit | get the attributes and methods of the parent | rex.eat() |
super() | the parent, used to call its methods | super().__init__(name, age) |
| Override | replace a parent's method in the child | Dog.speak |
Try it yourself
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
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
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:
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:
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:
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
| Idea | In plain words | In Python |
|---|---|---|
| Encapsulation | keep data and methods together, protect the data | a class, self._balance, methods that check |
| Abstraction | a simple method hides the steps | make_coffee() calls _heat_water(), _grind_beans(), _pour() |
| Inheritance | a child class gets everything from its parent | class Dog(Animal):, super().__init__(...) |
| Polymorphism | the same method name, a different result per class | for shape in shapes: shape.area() |
One small program with all four:
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:
Manageris anEmployeeand reuses its__init__anddescribe. - Polymorphism:
pay()gives a different result for a manager, anddescribe()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
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
speak(self) with the same name. The loop at the bottom is already written.Show the solution
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
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:
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
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.
| Form | How you use it | Good for |
|---|---|---|
import math | math.sqrt(16) | the usual way: it is clear where sqrt comes from |
from math import sqrt | sqrt(16) | one or two names that you use often |
import statistics as stats | stats.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
| Module | What it gives | Example |
|---|---|---|
math | mathematical functions | math.sqrt(16) |
random | random numbers and choices | random.randint(1, 6) |
statistics | mean, median and more | statistics.mean([1, 2, 3]) |
datetime | dates and times | datetime.date(2026, 10, 3) |
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:
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
import mathsError
ModuleNotFoundError: No module named 'maths'
7.7Your own module
Any .py file is a module. Suppose you save this as shapes.py:
# 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 ** 2Another file in the same folder can use it:
# 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.pyfrom school import grades
from school.students import Student7.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:
import numpy as np
import pandas as pdnp and pd are the short names everybody uses. The rest of this course is built on such packages: NumPy, pandas, Matplotlib and scikit-learn.
| Word | Meaning | Example |
|---|---|---|
| Module | one .py file | math, your shapes.py |
| Package | a folder of modules | numpy, pandas |
| Standard library | the modules that come with Python | math, random, datetime |
pip / conda | tools that install packages | pip install numpy |
Try it yourself
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
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: RexNameError, 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: RexThe 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 5TypeError. 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 85The 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: -5000Right
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, 150Wrong 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: FalseRight
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: TrueYou 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:
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:
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__(...):
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
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
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
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
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
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)
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)
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)
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)
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
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
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
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
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
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
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.Write a class
Circlewith the attributeradiusand a methodarea()that returns the area. Usemath.pi.Examples:1gives3.142gives12.570gives0.0Show a hint
__init__(self, radius)stores the radius inself.radius. The area ismath.pi * self.radius ** 2. Return it, do not print it.Show one possible solution
Pythonimport 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.Write a class
Counterwith a methodincrease()and a methodreset(). The counter starts at 0, in an attribute calledvalue.Show a hint
__init__(self)setsself.value = 0.increaseadds 1 toself.value, andresetsets it back to 0.Show one possible solution
Pythonclass 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.Add a
__str__method to a classStudent(name and grade), so thatprint(student)shows a text likeAylin: 85.Examples:Aylin 85givesAylin: 85Murad 42givesMurad: 42Leyla 100givesLeyla: 100Show a hint
Write__init__(self, name, grade)first.__str__(self)must return the text:return f"{self.name}: {self.grade}".Show one possible solution
Pythonclass 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.Use the
statisticsmodule to print the mean and the median of[4, 8, 15, 16, 23, 42], each on its own line.Show a hint
The functions arestatistics.mean(numbers)andstatistics.median(numbers).Show one possible solution
Pythonimport 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.
- 5.Write a class
Temperaturethat stores degrees Celsius and has a methodto_fahrenheit(). The formula is F = C × 9 / 5 + 32.Examples:25gives77.00gives32.0100gives212.0Show a hint
Store the value in__init__. The method returnsself.celsius * 9 / 5 + 32.Show one possible solution
Pythonclass 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
- 6.Write a class
BankAccountwithdepositandwithdraw. A withdrawal larger than the balance must printnot enough moneyand leave the balance unchanged. The class takes the starting balance and keeps it in an attribute calledbalance.Show a hint
Inwithdraw, checkif amount > self.balance:first. Print the message andreturn, so the line that subtracts is not reached.Show one possible solution
Pythonclass 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
- 7.Write a class
Person(name) and a child classTeacher(name and subject). Usesuper().__init__. A methodintroduce()inTeacherreturns a sentence with both values, likeI am Aylin and I teach Python.Examples:Aylin PythongivesI am Aylin and I teach PythonMurad SQLgivesI am Murad and I teach SQLLeyla StatisticsgivesI am Leyla and I teach StatisticsShow a hint
class Teacher(Person):. In its__init__, callsuper().__init__(name)first, then store the subject.introducereturns an f-string.Show one possible solution
Pythonclass 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
- 8.Write a class
Rectanglewitharea()and a child classSquarethat takes only one side.Examples:4gives16 True1gives1 True0gives0 TrueShow a hint
A square is a rectangle with equal sides.Square.__init__(self, side)needs one line:super().__init__(side, side).areais inherited.Show one possible solution
Pythonclass 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
- 9.Write a class
ShoppingListthat keeps its items in an internal list and has the methodsadd(item),remove(item)andcount().Show a hint
__init__createsself._items = []. The three methods use the list methods you know:append,removeandlen.Show one possible solution
Pythonclass 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.
- 10.Write a class
Studentwith a name and an internal list of grades. Methods:add_grade(grade)(it raises aValueErrorif the grade is not from 0 to 100),average()andbest().Examples:85 92 78gives85.0 92 0100 150 50gives75.0 100 160gives60.0 60 0Show a hint
__init__(self, name)createsself._grades = []. Inadd_grade, check the range first andraise ValueError(...), then append.averageusessumandlen,bestusesmax.Show one possible solution
Pythonclass 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
- 11.Write classes
Shape,Rectangle,CircleandTriangle, each witharea(). Put several shapes in a list and print the name of the shape with the largest area. Each shape has an attributename:"rectangle","circle"or"triangle". A triangle takes a base and a height.Show a hint
The parentShapestores the name. Each child callssuper().__init__("rectangle")with its own name and definesarea(). The area of a triangle is base × height / 2.Show one possible solution
Pythonimport 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
- 12.Write a class
Employeewithpay(), and child classesManager(salary plus bonus) andIntern(half of the salary). Print the total pay of a list of staff.Show a hint
Employeestores the name and the salary, andpay()returns the salary.Manageradds a bonus in its own__init__(withsuper().__init__) and overridespay.Internonly overridespay.Show one possible solution
Pythonclass 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
- 13.Write a class
Stackwithpush(item),pop()andis_empty().pop()on an empty stack raises anIndexErrorwith your own message:the stack is empty.Show a hint
Keep the items inself._items = [].pushappends,popremoves and returns the last item. Inpop, first checkif self.is_empty():andraise IndexError("the stack is empty").Show one possible solution
Pythonclass 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
- 14.Write a class
Inventorythat keeps products and their amounts in an internal dictionary. Methods:add(name, amount),remove(name, amount)(it raises aValueErrorif there is not enough), andreport()that returns the names in alphabetical order. The error message isnot enoughand the name, likenot enough notebook.Show a hint
adduses the counting pattern:self._products[name] = self._products.get(name, 0) + amount.removechecks the amount first and raises.reportreturnssorted(self._products).Show one possible solution
Pythonclass 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']
- 15.Write a class
Clockwith hours and minutes and a methodtick()that adds one minute. After 23:59 comes 00:00.__str__shows the time like09:05.Examples:9 4gives09:0523 59gives00:000 0gives00:01Show a hint
Intick, 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
Pythonclass 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.
0 of 12 answered.
12Quick summary
| Concept | What it does | Example |
|---|---|---|
| Class | the plan for a kind of object | class Dog: |
| Object (instance) | one real thing made from a class | rex = Dog("Rex", 3) |
__init__ | runs when an object is created | def __init__(self, name): |
self | the object itself | self.name = name |
| Attribute | data of an object | rex.name |
| Method | an action of an object | rex.bark() |
__str__ | the text that print shows | def __str__(self): |
| Encapsulation | data and methods together, data protected | self._balance, deposit() |
| Abstraction | a simple method hides the steps | machine.make_coffee() |
| Inheritance | a child class gets everything from its parent | class Dog(Animal): |
super() | calls a method of the parent | super().__init__(name) |
| Polymorphism | the same method name, different behaviour | for s in shapes: s.area() |
import | loads a module | import math |
from ... import | loads chosen names | from math import sqrt |
as | gives a shorter name | import numpy as np |
| Package | a folder of modules, often installed with pip | pip install numpy |