Skip to content
7 changes: 7 additions & 0 deletions sprint5-prep-exercises/LimiOfTypeCheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def double(number):
# return number * 3
return number * 2

print(double(10))
# The bug is that the double function multiplies the number by 3 instead of 2.
# Since the function is called double, it should multiply the number by 2.
58 changes: 58 additions & 0 deletions sprint5-prep-exercises/PredictInheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Parent class stores a person's first name and last name
class Parent:
def __init__(self, first_name: str, last_name: str):
self.first_name = first_name
self.last_name = last_name
# Returns the person's first and last name together
def get_name(self) -> str:
return f"{self.first_name} {self.last_name}"

# Child inherits the fields and methods from Parent
# It also allows the person to change their last name
class Child(Parent):
def __init__(self, first_name: str, last_name: str):
super().__init__(first_name, last_name)
self.previous_last_names = []
# Changes the last name and saves the old name
def change_last_name(self, last_name) -> None:
self.previous_last_names.append(self.last_name)
self.last_name = last_name
# Returns the current name and the original last name
def get_full_name(self) -> str:
suffix = ""
if len(self.previous_last_names) > 0:
suffix = f" (née {self.previous_last_names[0]})"
return f"{self.first_name} {self.last_name}{suffix}"
# Create child object
person1 = Child("Elizaveta", "Alekseeva")
# Child inherits get_name() from Parent
# Output: Elizaveta Alekseeva
print(person1.get_name())
# Child has its own get_full_name() method
# Output: Elizaveta Alekseeva
print(person1.get_full_name())
# Change the last name
person1.change_last_name("Tyurina")
# The current last name is now Tyurina
# Output: Elizaveta Tyurina
print(person1.get_name())
# Shows the new name and the previous last name
# Output: Elizaveta Tyurina (née Alekseeva)
print(person1.get_full_name())
# Create a Parent object
person2 = Parent("Elizaveta", "Alekseeva")
# Parent has get_name(), so this works
# Output: Elizaveta Alekseeva
print(person2.get_name())
# This causes an AttributeError because Parent
# does not have a get_full_name() method
print(person2.get_full_name())
# This also causes an AttributeError because Parent
# does not have a change_last_name() method
person2.change_last_name("Tyurina")
# get_name() still works because it belongs to Parent
# Output: Elizaveta Alekseeva
print(person2.get_name())
# This would cause another AttributeError
# because get_full_name() only exists in Child
print(person2.get_full_name())
11 changes: 11 additions & 0 deletions sprint5-prep-exercises/accessNotExiProp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Person:
def __init__(self, name: str):
self.name = name

def get_name(person: Person) -> str:
return person.name

def get_age(person: Person) -> int:
return person.age
# As I expected, mypy prints an error saying that Person has no attribute name,
# because the age property does not exist in the Person class.
17 changes: 17 additions & 0 deletions sprint5-prep-exercises/classesAndObjects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Person:
def __init__(self, name: str, age: int, preferred_operating_system: str):
self.name = name
self.age = age
self.preferred_operating_system = preferred_operating_system

imran = Person("Imran", 22, "Ubuntu")
print(imran.name)
print(imran.address)

eliza = Person("Eliza", 34, "Arch Linux")
print(eliza.name)
print(eliza.address)


# The error means that address doesn't exist in the Person class. We can only
# access attributes that were defined in the class, such as name, age, and preferred_operating_system.
96 changes: 96 additions & 0 deletions sprint5-prep-exercises/enums.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation works, but could the UX and input validation be improved?

Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from dataclasses import dataclass
from enum import Enum
import sys


class OperatingSystem(Enum):
MACOS = "macOS"
ARCH = "Arch Linux"
UBUNTU = "Ubuntu"


@dataclass(frozen=True)
class Person:
name: str
age: int
preferred_operating_system: OperatingSystem


@dataclass(frozen=True)
class Laptop:
id: int
manufacturer: str
model: str
screen_size_in_inches: float
operating_system: OperatingSystem


laptops = [
Laptop(1, "Dell", "XPS", 13, OperatingSystem.ARCH),
Laptop(2, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
Laptop(3, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
Laptop(4, "Apple", "MacBook", 13, OperatingSystem.MACOS),
]


# Get the person's name
name = input("What is your name? ")


# Get and convert age
try:
age = int(input("What is your age? "))
except ValueError:
print("Age must be a number.", file=sys.stderr)
sys.exit(1)


# Get and convert operating system
try:
os_input = input("What is your preferred operating system? ")
operating_system = OperatingSystem(os_input)
except ValueError:
print("Invalid operating system.", file=sys.stderr)
sys.exit(1)


person = Person(
name=name,
age=age,
preferred_operating_system=operating_system,
)


# Count laptops with the person's preferred OS
number_available = sum(
laptop.operating_system == person.preferred_operating_system
for laptop in laptops
)


print(
f"We have {number_available} laptop(s) with "
f"{person.preferred_operating_system.value}."
)


# Find the operating system with the most laptops
counts = {}

for os in OperatingSystem:
counts[os] = sum(
laptop.operating_system == os
for laptop in laptops
)


most_available_os = max(counts, key=counts.get)


if most_available_os != person.preferred_operating_system:
if counts[most_available_os] > number_available:
print(
f"If you are willing to use {most_available_os.value}, "
f"you are more likely to get a laptop because we have "
f"{counts[most_available_os]} available."
)
23 changes: 23 additions & 0 deletions sprint5-prep-exercises/methods.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think one of the tasks, explaining the difference between functions and methods is missing

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import datetime as dt
from dataclasses import dataclass


@dataclass
class Person:
name: str
birthdate: dt.date
preferred_operating_system: str

def is_adult(self) -> bool:
today = dt.date.today()
age = today.year - self.birthdate.year

if (today.month, today.day) < (self.birthdate.month, self.birthdate.day):
age -= 1

return age >= 18


imran = Person("Imran", dt.date(2000, 8, 6), "Ubuntu")

print(imran.is_adult())
13 changes: 13 additions & 0 deletions sprint5-prep-exercises/predictDouble.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def half(value):
return value / 2

def double(value):
return value * 2

def second(value):
return value[1]


print(double("22"))
# I predicted that it would return an error, but it actually returned 2222.
# I didn't expect this because I thought double() was supposed to work only with numbers.
48 changes: 48 additions & 0 deletions sprint5-prep-exercises/prefOperatingSys.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from dataclasses import dataclass
from typing import List

@dataclass(frozen=True)
class Person:
name: str
age: int
preferred_operating_systems: list[str]


@dataclass(frozen=True)
class Laptop:
id: int
manufacturer: str
model: str
screen_size_in_inches: float
operating_system: str


def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
possible_laptops = []
for laptop in laptops:
if laptop.operating_system == person.preferred_operating_systems:
possible_laptops.append(laptop)
return possible_laptops


people = [
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu"]),
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux"]),
]

laptops = [
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system="Arch Linux"),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="Ubuntu"),
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="ubuntu"),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system="macOS"),
]

for person in people:
possible_laptops = find_possible_laptops(laptops, person)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I run this, I get empty output. Do you see that? Why do you think this happens?

print(f"Possible laptops for {person.name}: {possible_laptops}")



# Yes, at first, when I changed str to list[str],
# mypy showed errors as I expected because I was still passing strings instead of lists
# Then I changed the field name to the plural form `preferred_operating_systems` to match the fact that it is now a list.
39 changes: 39 additions & 0 deletions sprint5-prep-exercises/typeAnnotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

def open_account(balances: dict[str, int], name: str, amount: int):
balances[name] = amount


def sum_balances(accounts: dict[str, int]) -> int:
total = 0
for name, pence in accounts.items():
print(f"{name} had balance {pence}")
total += pence
return total


def format_pence_as_string(total_pence: int) -> str:
if total_pence < 100:
return f"{total_pence}p"
pounds = int(total_pence / 100)
pence = total_pence % 100
return f"£{pounds}.{pence:02d}"


balances: dict[str, int] = {
"Sima": 700,
"Linn": 545,
"Georg": 831,
}


open_account(balances, "Tobi", 913)
open_account(balances, "Olya", 713)

total_pence = sum_balances(balances)
total_string = format_pence_as_string(total_pence)

print(f"The bank accounts total {total_string}")
def is_adult(person: Person) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these last few lines in the right file?

return person.age >= 18

print(is_adult(imran))