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
36 changes: 36 additions & 0 deletions Урок 8. Практическое задание/task_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,39 @@
Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца
и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных.
"""

class OwnDate:
def __init__(self, day_month_year):
self.day_month_year = str(day_month_year)

@classmethod
def extract(cls, day_month_year):
date = []

for i in day_month_year.split():
if i != '-':
date.append(i)

return int(date[0]), int(date[1]), int(date[2])

@staticmethod
def valid(day, month, year):

if day not in range(1, 32):
return f'День указан некорретно'
if month not in range(1, 13):
return f'Месяц укaзан некорретно'
if year not in range(0, 2100):
return f'Год указан некорретно'
return f'Данные укaзаны корректно'

def __str__(self):
return f'Дата на сегодня {OwnDate.extract(self.day_month_year)}'


today = OwnDate('22 - 6 - 2023')
print(today)
print(OwnDate.valid(31, 11, 2022))
print(today.valid(15, 18, 1990))
print(OwnDate.extract('31 - 9 - 2021'))
print(today.extract('22 - 6 - 2023'))
Copy link
Owner

Choose a reason for hiding this comment

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

выполнено

19 changes: 19 additions & 0 deletions Урок 8. Практическое задание/task_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,22 @@
Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля
в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
"""
class Own_error(Exception):
Copy link
Owner

Choose a reason for hiding this comment

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

нарушение пеп-8 в именах классов

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

def div_by_null():
try:
div = int(input('Ввод делимого: '))
denominator = int(input('Ввод делителя: '))
if denominator == 0:
raise Own_error("На ноль делить нельзя")
else:
quotient = div / denominator
return quotient
except ValueError:
return "Введено не число"
except Own_error as err:
return err

print(div_by_null())
32 changes: 32 additions & 0 deletions Урок 8. Практическое задание/task_3.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,35 @@

Класс-исключение должен контролировать типы данных элементов списка.
"""

def Is_integer(v):
Copy link
Owner

Choose a reason for hiding this comment

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

также имена

try:
float(v)
except ValueError:
return False
else:
return float(v).Is_integer()


class MyException(Exception):
def __init__(self, txt):
self.txt = txt


int_lst = []
while True:
try:
input_data = input("Ввести число для cписка (для выходa введите / ) : ")

if input_data == "/":
break

if not Is_integer(input_data):
raise MyException(input_data)

int_lst.append(int(input_data))
except MyException as err:
print("Введено не число, повторите попытку")

print(f"Результат: {int_lst}")

61 changes: 61 additions & 0 deletions Урок 8. Практическое задание/task_4_5_6.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,64 @@
Подсказка: постарайтесь по возможности реализовать в проекте
«Склад оргтехники» максимум возможностей, изученных на уроках по ООП.
"""

class Warehouse:

def __init__(self, name, price, quantity, number_of_lists, *args):
self.name = name
self.price = price
self.quantity = quantity
self.numb = number_of_lists
self.my_warehouse_full = []
self.my_warehouse = []
self.my_unit = {'Модель устройства': self.name, 'Цена за ед. товара': self.price, 'Количество': self.quantity}

def __str__(self):
return f'{self.name} цена {self.price} количество {self.quantity}'

def reception(self):
try:
unit = input(f'Ввод модели устройства: ')
price = int(input(f'Ввод цены цены устройства за единицу в рублях: '))
qty = int(input(f'Ввод количества товара: '))
unique = {'Модель устройства': unit, 'Цена за ед.товара': price, 'Количество': qty}
self.my_unit.update(unique)
self.my_warehouse.append(self.my_unit)
print(f'Текущий список: \n {self.my_warehouse}')
except:
return f'Ошибка ввода данных'

print(f'Для выхода ввести ex, для продолжения нажать Enter ')
q = input()
if q == 'ex':
self.my_warehouse_full.append(self.my_warehouse)
print(f'Весь склад: \n {self.my_warehouse_full}')
return f'Выход '
else:
return Warehouse.reception(self)


class Printer(Warehouse):
def to_print(self):
return f'напечатать стр.{self.numb} раз'


class Scanner(Warehouse):
def to_scan(self):
return f'отсканировать лист {self.numb} раз'


class Copier(Warehouse):
def to_copier(self):
return f'копировать лист {self.numb} раз'


unit_1 = Printer('Samsung', 8500, 10, 30)
unit_2 = Scanner('HP', 6550, 7, 25)
unit_3 = Copier('Xerox', 4600, 3, 33)
print(unit_1.reception())
print(unit_2.reception())
print(unit_3.reception())
print(unit_1.to_print())
print(unit_2.to_scan())
print(unit_3.to_copier())
Copy link
Owner

Choose a reason for hiding this comment

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

выполнено

21 changes: 21 additions & 0 deletions Урок 8. Практическое задание/task_7.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,24 @@
создав экземпляры класса (комплексные числа) и выполнив сложение и умножение созданных экземпляров.
Проверьте корректность полученного результата.
"""

class ComplexNumber:
def __init__(self, a, b):
self.a = a
self.b = b

def __add__(self, other):
return f'Сумма: {self.a + other.a} + {self.b + other.b}i'


def __mul__(self, other):
return f'Произведение: {(self.a * other.a) - (self.b * other.b)} {self.b * other.a}i'


def __str__(self):
return f'{self.a}{"+" if self.b > 0 else ""}{self.b}i'

first_numbers = ComplexNumber(8, 6)
second_numbers = ComplexNumber(-98, 7)
print(first_numbers + second_numbers)
print(first_numbers * second_numbers)
Copy link
Owner

Choose a reason for hiding this comment

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

выполнено