Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions level_1/a_user_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ def __init__(self, name: str, username: str, age: int, phone: str):
self.age = age
self.phone = phone

def __str__(self) -> str:
return f"Информация о пользователе: {self.name}, {self.username}, {self.age}, {self.phone}"

if __name__ == '__main__':
pass # код писать тут

if __name__ == "__main__":
print(User("john smith", "john_smith", 35, "+78003598989"))
8 changes: 5 additions & 3 deletions level_1/b_student_full_name_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ def __init__(self, name: str, surname: str, faculty: str, course: int):
self.surname = surname
self.faculty = faculty
self.course = course
self.full_name = ""

def get_full_name(self):
return f"Student's full name: {self.surname}, {self.name}"


if __name__ == '__main__':
pass # код писать тут

if __name__ == "__main__":
student = Student(name="john", surname="smith", faculty="economy", course=2)
student.full_name = student.get_full_name()
print(student.full_name)
24 changes: 21 additions & 3 deletions level_1/c_product_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,26 @@


class Product:
pass # код писать тут
def __init__(
self, title: str, description: str, price: float, weight: float
) -> None:
self.title = title
self.description = description
self.price = price
self.weight = weight

def __str__(self) -> str:
return f"Информация о продукте: {self.title}, {self.description}, {self.price}, {self.weight}"

if __name__ == '__main__':
pass # код писать тут

if __name__ == "__main__":
str1 = "Конструкция пишущего узла шариковых ручек представляет собой металлическую трубку из нержавеющей стали."
str2 = "Между ее стенками располагается маленький вольфрамовый шарик."
str3 = "Во время его движения по бумаге он «обмазывается» пастообразными чернилами со стороны стержня."
product = Product(
title="Ручка шариковая",
description=f"{str1} {str2} {str3}",
price=15.55,
weight=0.01,
)
print(product)
9 changes: 6 additions & 3 deletions level_1/d_bank_account_increase_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ def __init__(self, owner_full_name: str, balance: float):
self.balance = balance

def increase_balance(self, income: float):
pass # код писать тут
self.balance += income


if __name__ == '__main__':
pass # код писать тут
if __name__ == "__main__":
bank_account = BankAccount("john smith", 100.0)
print(f"Баланс: {bank_account.balance}")
bank_account.increase_balance(35.25)
print(f"Баланс: {bank_account.balance}")
20 changes: 17 additions & 3 deletions level_1/e_bank_account_decrease_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,22 @@


class BankAccount:
pass # код писать тут
def __init__(self, owner_full_name: str, balance: float):
self.owner_full_name = owner_full_name
self.balance = balance

def increase_balance(self, income: float):
self.balance += income

if __name__ == '__main__':
pass # код писать тут
def decrease_balance(self, cost: float):
if self.balance - cost < 0:
raise ValueError("balance must be above zero")
self.balance -= cost


if __name__ == "__main__":
bank_account = BankAccount("john smith", 100.0)
print(f"Баланс: {bank_account.balance}")
bank_account.decrease_balance(35.25)
print(f"Баланс: {bank_account.balance}")
bank_account.decrease_balance(100.0)
22 changes: 19 additions & 3 deletions level_2/a_user_from_functions_to_class.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""""
""" "
У нас есть функции для работы с пользователем, но хочется работать с ним через класс.

Задания:
Expand All @@ -11,8 +11,24 @@ def make_username_capitalized(username: str):


def generate_short_user_description(username: str, user_id: int, name: str):
return f'User with id {user_id} has {username} username and {name} name'
return f"User with id {user_id} has {username} username and {name} name"


class User:
pass # код писать тут
def __init__(self, user_id: int, name: str, username: str) -> None:
self.user_id = user_id
self.name = name
self.username = username

def make_username_capitalized(self) -> str:
return self.username.capitalize()

def generate_short_user_description(self) -> str:
return f"User with id {self.user_id} has {self.username} username and {self.name} name"


if __name__ == "__main__":
user = User(user_id=1, name="john smith", username="john smith")
print(
f"{user.name}, {user.make_username_capitalized()}, {user.generate_short_user_description()}"
)
18 changes: 16 additions & 2 deletions level_2/b_user_should_be_banned.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,22 @@
Пользователя стоит забанить, если его фамилия находится в SURNAMES_TO_BAN.
"""

SURNAMES_TO_BAN = ['Vaughn', 'Wilhelm', 'Santaros', 'Porter', 'Smith']
SURNAMES_TO_BAN = ["Vaughn", "Wilhelm", "Santaros", "Porter", "Smith"]


class User:
pass # код писать тут
def __init__(self, name: str, username: str, age: int):
self.name = name
self.username = username
self.age = age

def should_be_banned(self) -> bool:
return self.name in SURNAMES_TO_BAN


if __name__ == "__main__":
user1 = User(name="Smith", username="john smith", age=35)
print(f"{user1.name} should_be_banned : {user1.should_be_banned()}")

user2 = User(name="Croft", username="lara croft", age=25)
print(f"{user2.name} should_be_banned : {user2.should_be_banned()}")
20 changes: 14 additions & 6 deletions level_3/a_credit_bank_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
4. Создать экземпляр класс CreditAccount и вызвать у него каждый из возможных методов.
"""

# код писать тут


class CreditAccount:
class BankAccount:
def __init__(self, owner_full_name: str, balance: float):
self.owner_full_name = owner_full_name
self.balance = balance
Expand All @@ -22,10 +20,20 @@ def increase_balance(self, amount: float):
def decrease_balance(self, amount: float):
self.balance -= amount


class CreditAccount(BankAccount):
def is_eligible_for_credit(self):
return self.balance > 1000


if __name__ == '__main__':
pass # код писать тут

if __name__ == "__main__":
ba1 = BankAccount("Vasya", 1000.99)
ba1.increase_balance(548.98)
ba1.decrease_balance(125.54)
print(f"balance: {ba1.balance}")
ca1 = CreditAccount("Petya", 465.88)
ca1.increase_balance(1110.30)
ca1.decrease_balance(125.00)
print(
f"balance: {ca1.balance}, is_eligible_for_credit: {ca1.is_eligible_for_credit()}"
)
39 changes: 33 additions & 6 deletions level_3/b_user_manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,36 @@ def get_users(self):
return self.usernames


# код писать тут


if __name__ == '__main__':
pass # код писать тут

class AdminManager(UserManager):
def ban_username(self, username: str):
if username not in self.get_users():
print("Такого пользователя не существует.")
return
self.usernames.remove(username)


class SuperAdminManager(AdminManager):
def ban_all_users(self):
self.usernames.clear()


if __name__ == "__main__":
um1 = UserManager()
um1.add_user("Vasya")
um1.add_user("Petya")
um1.add_user("Slava")

am1 = AdminManager()
am1.add_user("Vasya")
am1.add_user("Petya")
am1.add_user("Slava")
am1.ban_username("Slava")
am1.ban_username("Tolya")

sam1 = SuperAdminManager()
sam1.add_user("Vasya")
sam1.add_user("Petya")
sam1.add_user("Slava")
sam1.ban_username("Slava")
sam1.ban_username("Tolya")
sam1.ban_all_users()
27 changes: 21 additions & 6 deletions level_3/c_text_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,26 @@ def to_upper(self):
return self.text.upper()

def summarize(self):
return f'Total text length: {len(self.text)}'
return f"Total text length: {len(self.text)}"


# код писать тут


if __name__ == '__main__':
pass # код писать тут
class AdvancedTextProcessor(TextProcessor):
def summarize(self):
total_text_length = len(self.text)
total_number_of_words = len(self.text.split())
return f"Total text length: {total_text_length}, total number of words in the text: {total_number_of_words}"


if __name__ == "__main__":
some_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,\
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
tp1 = TextProcessor(some_text)
print(tp1.to_upper())
print(tp1.summarize())

atp1 = AdvancedTextProcessor(some_text)
print(atp1.to_upper())
print(atp1.summarize())
10 changes: 7 additions & 3 deletions level_3/d_alcohol_product.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Для определения текущего часа можно использовать datetime.now().hour
3. Создайте экземпляр класса AlcoholProduct и проверьте, можно ли сейчас продавать алкоголь.
"""

from datetime import datetime


Expand All @@ -26,8 +27,11 @@ def is_available(self):


class AlcoholProduct(Product):
pass # код писать тут
def is_available(self):
available_hours = [hour for hour in range(5, 23)]
return super().is_available() and datetime.now().hour in available_hours


if __name__ == '__main__':
pass # код писать тут
if __name__ == "__main__":
ap1 = AlcoholProduct("beer", 50.5, 10)
print(ap1.is_available())
28 changes: 21 additions & 7 deletions level_6/a_log_products.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,47 @@
"""


class PrintLoggerMixin:
def log(self, message: str):
print(message)


class Product:
def __init__(self, title: str, price: float):
self.title = title
self.price = price

def get_info(self):
return f'Product {self.title} with price {self.price}'
return f"Product {self.title} with price {self.price}"


class PremiumProduct(Product):
class PremiumProduct(Product, PrintLoggerMixin):
def increase_price(self):
self.price *= 1.2
self.log("increase_price method PremiumProduct class was called")

def get_info(self):
base_info = super().get_info()
return f'{base_info} (Premium)'
self.log("get_info method PremiumProduct class was called")
return f"{base_info} (Premium)"


class DiscountedProduct(Product):
class DiscountedProduct(Product, PrintLoggerMixin):
def decrease_price(self):
self.price /= 1.2
self.log("decrease_price method DiscountedProduct class was called")

def get_info(self):
base_info = super().get_info()
return f'{base_info} (Discounted)'
self.log("get_info method DiscountedProduct class was called")
return f"{base_info} (Discounted)"


if __name__ == '__main__':
pass
if __name__ == "__main__":
pp1 = PremiumProduct("milk", 79.49)
pp1.increase_price()
print(pp1.get_info())

dp1 = DiscountedProduct("bread", 49.99)
dp1.decrease_price()
print(dp1.get_info())
17 changes: 13 additions & 4 deletions level_6/b_developer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(self, name: str, surname: str, age: int, salary: float):
self.salary = salary

def get_info(self):
return f'{self.name} with salary {self.salary}'
return f"{self.name} with salary {self.salary}"


class ItDepartmentEmployee(Employee):
Expand All @@ -35,9 +35,18 @@ def decrease_salary(self, employee: Employee, amount: float):
employee.salary -= amount


# код писать тут
class Developer(ItDepartmentEmployee, SuperAdminMixin):
def __init__(self, name: str, surname: str, age: int, salary: float, lang: str):
super().__init__(name, surname, age, salary)
self.lang = lang

def get_info(self):
return f"{super().get_info()} by {self.lang}"

if __name__ == '__main__':
pass # код писать тут

if __name__ == "__main__":
dev = Developer("denis", "pekshev", 40, 40000.0, "python")
print(dev.get_info())
dev.increase_salary(dev, 3000.0)
dev.decrease_salary(dev, 6000.0)
print(dev.get_info())
Loading