From 2ea67be862c147acc725dd603010e519ef1b64f3 Mon Sep 17 00:00:00 2001 From: Pavel Date: Sun, 3 Apr 2022 17:19:53 +0300 Subject: [PATCH 1/7] Done. --- Lesson_8/task_1.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Lesson_8/task_1.py diff --git a/Lesson_8/task_1.py b/Lesson_8/task_1.py new file mode 100644 index 0000000..3110cb6 --- /dev/null +++ b/Lesson_8/task_1.py @@ -0,0 +1,60 @@ +# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». +# В рамках класса реализовать два метода. Первый, с декоратором @classmethod. +# Он должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». +# Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца и года (например, месяц — от 1 до 12). +# Проверить работу полученной структуры на реальных данных. + +class Date: + def __init__(self, d_m_y): + self.d_m_y = str(d_m_y) + + @classmethod + def extraction(cls, d_m_y): + my_date = [] + + for i in d_m_y.split(): + if i != '/': + my_date.append(i) + + return int(my_date[0]), int(my_date[1]), int(my_date[2]) + + @staticmethod + def validation(d, m, y): + # if 1 <= d <= 31: + # return f'Date is correct!' + # else: + # f'Incorrect day' + # + # if 1 <= m <= 12: + # return f'Date is correct!' + # else: + # f'Incorrect month' + # + # if 0 <= y <= 2022: + # return f'Date is correct!' + # else: + # f'Incorrect year' + + if 1 <= d <= 31: + if 1 <= m <= 12: + if 988 <= y <= 2050: + return f'The entered date is correct.' + else: + return f'Please enter correct year.' + else: + return f'Please enter correct month.' + else: + return f'Please enter correct day.' + + def __str__(self): + return f'The current date is: {Date.extraction(self.d_m_y)}' + + +day = Date('3 / 4 / 2000') +print(day) + +print(Date.validation(16, 6, 2022)) +print(Date.validation(3, 15, 2000)) +print(day.validation(3, 4, 950)) +print(Date.extraction('3 / 4 / 2022')) +print(day.extraction('3 / 4 / 2022')) From 8cb52b9be970b660319163a476a4acb7ad8ff2c6 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 4 Apr 2022 20:04:13 +0300 Subject: [PATCH 2/7] Almost done. Would like to improve. --- Lesson_8/task_2.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Lesson_8/task_2.py diff --git a/Lesson_8/task_2.py b/Lesson_8/task_2.py new file mode 100644 index 0000000..df90251 --- /dev/null +++ b/Lesson_8/task_2.py @@ -0,0 +1,22 @@ +# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. +# Проверьте его работу на данных, вводимых пользователем. +# При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию +# и не завершиться с ошибкой. + +class Division: + def __init__(self, divident, divider): + self.divident = divident + self.divider = divider + + @staticmethod + def division_by_null(divident, divider): + try: + return (divident / divider) + except: + return (f'Division by null is not allowed!') + + +div = Division(25, 5) +print(Division.division_by_null(25, 0)) +print(Division.division_by_null(45, 5)) +print(div.division_by_null(25, 0)) From 3b131e32c131de4635f660b10d74297a8955ae8c Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 5 Apr 2022 17:15:04 +0300 Subject: [PATCH 3/7] Almost done. Need to improve. --- Lesson_8/task_3.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Lesson_8/task_3.py diff --git a/Lesson_8/task_3.py b/Lesson_8/task_3.py new file mode 100644 index 0000000..1b5dcb9 --- /dev/null +++ b/Lesson_8/task_3.py @@ -0,0 +1,25 @@ +# Создайте собственный класс-исключение, который должен проверять содержимое списка на наличие только чисел. +# Проверить работу исключения на реальном примере. Запрашивать у пользователя данные и заполнять список +# необходимо только числами. Класс-исключение должен контролировать типы данных элементов списка. + +class MyOwnErr: + def __init__(self, *args): + self.my_list = [] + + def content(self): + while True: + try: + value = int(input('Please enter a number: ')) + self.my_list.append(value) + print(f'The current list is: {self.my_list} \n') + except: + print('This value is not allowed!') + choice = input('Would you like to try again? (Y/N)? - ') + + if choice == 'Y' or choice == 'y': + print(my_exception.content()) + elif choice == 'N' or choice == 'n': + print('Exit done.') + +my_exception = MyOwnErr(1) +print(my_exception.content()) \ No newline at end of file From 62c1296d253f01a9e22d6fe7654759716327ea99 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 5 Apr 2022 17:36:24 +0300 Subject: [PATCH 4/7] Made some changes. Got worse. Now all the time displays about the incorrectness of the entered value and requests to continue. --- Lesson_8/task_3.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Lesson_8/task_3.py b/Lesson_8/task_3.py index 1b5dcb9..2b35807 100644 --- a/Lesson_8/task_3.py +++ b/Lesson_8/task_3.py @@ -3,23 +3,27 @@ # необходимо только числами. Класс-исключение должен контролировать типы данных элементов списка. class MyOwnErr: - def __init__(self, *args): + def __init__(self, value): + self.value = value self.my_list = [] - def content(self): + def content(self, value): while True: try: - value = int(input('Please enter a number: ')) - self.my_list.append(value) - print(f'The current list is: {self.my_list} \n') - except: - print('This value is not allowed!') - choice = input('Would you like to try again? (Y/N)? - ') + value = int(input(f'Please enter a number: ')) + self.my_list.append(value) + print(f'The current list is: {self.my_list} \n') + finally: + if type(value) != int(): + print(f'This value is not allowed!') + + choice = input(f'Would you like to try again? (Y/N)? - ') if choice == 'Y' or choice == 'y': - print(my_exception.content()) + print(my_exception.content(value)) elif choice == 'N' or choice == 'n': - print('Exit done.') + print(f'Exit done.') + my_exception = MyOwnErr(1) -print(my_exception.content()) \ No newline at end of file +print(my_exception.content(0)) From 69ea0c8de5aa74b39085106e0f06e1400bac12db Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 5 Apr 2022 17:42:42 +0300 Subject: [PATCH 5/7] Everything seems to be in order. --- Lesson_8/task_3.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lesson_8/task_3.py b/Lesson_8/task_3.py index 2b35807..440cf62 100644 --- a/Lesson_8/task_3.py +++ b/Lesson_8/task_3.py @@ -13,10 +13,10 @@ def content(self, value): value = int(input(f'Please enter a number: ')) self.my_list.append(value) print(f'The current list is: {self.my_list} \n') - finally: + except: if type(value) != int(): print(f'This value is not allowed!') - + else: choice = input(f'Would you like to try again? (Y/N)? - ') if choice == 'Y' or choice == 'y': From 1c082ea8319b4da36215868566afba6139aa7151 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 5 Apr 2022 17:52:29 +0300 Subject: [PATCH 6/7] in process... --- Lesson_8/task_7.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Lesson_8/task_7.py diff --git a/Lesson_8/task_7.py b/Lesson_8/task_7.py new file mode 100644 index 0000000..0cd0f4a --- /dev/null +++ b/Lesson_8/task_7.py @@ -0,0 +1,25 @@ +# Реализовать проект «Операции с комплексными числами». +# Создайте класс «Комплексное число». Реализуйте перегрузку методов сложения и умножения комплексных чисел. +# Проверьте работу проекта. Для этого создаёте экземпляры класса (комплексные числа), +# выполните сложение и умножение созданных экземпляров. Проверьте корректность полученного результата. + +class ComplexValue: + def __init__(self, a, b): + self.a = a + self.b = b + self.val = 'a + j * b' + + def __add__(self, other): + pass + + def __mul__(self, other): + pass + + def __str__(self): + pass + + +val_1 = ComplexValue(a, b) +val_2 = ComplexValue(a, b) +print(val_1 + val_2) +print(val_1 * val_2) From 531df1c4f0572aa168041b5744e994a73c4900ee Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 5 Apr 2022 19:11:15 +0300 Subject: [PATCH 7/7] Done. --- Lesson_8/task_7.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Lesson_8/task_7.py b/Lesson_8/task_7.py index 0cd0f4a..10bb067 100644 --- a/Lesson_8/task_7.py +++ b/Lesson_8/task_7.py @@ -10,16 +10,16 @@ def __init__(self, a, b): self.val = 'a + j * b' def __add__(self, other): - pass + print('The result of the addition is: ') + return f'val = {self.a + other.a} + {self.b + other.b}*j' def __mul__(self, other): - pass + print('The result of the multiplication is: ') + return f'val = ({self.a * other.a - self.b * other.b}) + ' \ + f'({self.a * other.b + self.b * other.a})*j' - def __str__(self): - pass - -val_1 = ComplexValue(a, b) -val_2 = ComplexValue(a, b) +val_1 = ComplexValue(2, 5) +val_2 = ComplexValue(1, -3) print(val_1 + val_2) print(val_1 * val_2)