From d33e52b3c58b18ba638eea1e98e7692886e754d8 Mon Sep 17 00:00:00 2001 From: kaplya-sys Date: Mon, 5 Sep 2022 20:54:19 +0500 Subject: [PATCH 1/4] completed 6 out of 8 --- 1_if1.py | 24 ++++++++++++++++++---- 2_if2.py | 22 ++++++++++++++++---- 3_for.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++--- 4_while1.py | 11 +++++----- 5_while2.py | 19 +++++++++++++---- 6_exception1.py | 15 +++++++++----- 6 files changed, 120 insertions(+), 25 deletions(-) diff --git a/1_if1.py b/1_if1.py index be736084..72718d1f 100644 --- a/1_if1.py +++ b/1_if1.py @@ -4,22 +4,38 @@ Условный оператор: Возраст -* Попросить пользователя ввести возраст при помощи input и положить +* Попросить пользователя ввести возраст при помощи input и положить результат в переменную -* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: +* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать -* Вызвать функцию, передав ей возраст пользователя и положить результат +* Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в переменную * Вывести содержимое переменной на экран """ +def distribute_career(age): + if age < 1.5: + return print('Ты совсем еще маленький') + elif 1.5 <= age <= 7: + return print('Ходить в детский сад') + elif 7 < age <= 18: + return print('Учиться в школе') + elif 18 < age <= 23: + return print('Учиться в ВУЗе') + elif 23 < age <= 70: + return print('Пора работать') + else: + return print('Пора уже на пенсию') + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + user_age = int(input('Введите ваш возраст: ')) + + distribute_career(user_age) if __name__ == "__main__": main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..c6c824e4 100644 --- a/2_if2.py +++ b/2_if2.py @@ -5,22 +5,36 @@ Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки -* Проверить, является ли то, что передано функции, строками. +* Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 -* Вызвать функцию несколько раз, передавая ей разные праметры +* Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ +def check_string(first_string, second_string): + if type(first_string) and type(second_string) != str: + return 0 + elif first_string == second_string: + return 1 + else: + if second_string == 'learn': + return 3 + elif len(first_string) > len(second_string): + return 2 + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + print(check_string('python', 2)) + print(check_string('python', 'python')) + print(check_string('python', 'js')) + print(check_string('python', 'learn')) + if __name__ == "__main__": main() diff --git a/3_for.py b/3_for.py index 5ca9f504..a678bb25 100644 --- a/3_for.py +++ b/3_for.py @@ -6,7 +6,7 @@ * Дан список словарей с данными по колличеству проданных телефонов [ - {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, + {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, {'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, ] @@ -16,12 +16,60 @@ * Посчитать и вывести среднее количество продаж всех товаров """ +phones = [ + {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, + {'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, + {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, + ] + +def get_total_sold(items_sold): + summ = 0 + for item in items_sold: + summ += item + return summ + +def get_average_sold(items_sold): + summ = 0 + for item in items_sold: + summ += item + return summ / len(items_sold) + +def total_sold_each_item(products): + items_summ = [] + for product in products: + item_summ_sold = get_total_sold(product['items_sold']) + items_summ.append({product['product']: item_summ_sold}) + return items_summ + +def total_sold_all_item(products): + all_summ = 0 + for product in products: + all_summ += get_total_sold(product['items_sold']) + return all_summ + +def average_sold_each_item(products): + items_summ = [] + for product in products: + item_summ_sold = get_average_sold(product['items_sold']) + items_summ.append({product['product']: item_summ_sold}) + return items_summ + +def average_sold_all_item(products): + all_summ = 0 + for product in products: + all_summ += get_average_sold(product['items_sold']) + return all_summ + + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + print(total_sold_each_item(phones)) + print(total_sold_all_item(phones)) + print(average_sold_each_item(phones)) + print(average_sold_all_item(phones)) + if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..9c26f302 100644 --- a/4_while1.py +++ b/4_while1.py @@ -4,18 +4,19 @@ Цикл while: hello_user -* Напишите функцию hello_user(), которая с помощью функции input() спрашивает +* Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” - -""" +""" def hello_user(): """ Замените pass на ваш код """ - pass + answer = '' + while answer != 'Хорошо': + answer = input('Как дела? ') + - if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..d1a417e7 100644 --- a/5_while2.py +++ b/5_while2.py @@ -12,16 +12,27 @@ Пользователь: Что делаешь? Программа: Программирую - + """ -questions_and_answers = {} +questions_and_answers = { + "Как дела?": "Хорошо!", + "Что делаешь?": "Программирую", + "Как успехи?": "Потихоньку вникаю", + "Трудно": "Пока нет)", + } def ask_user(answers_dict): """ Замените pass на ваш код """ - pass - + while True: + question = input('Введите вопрос: ') + answer = questions_and_answers.get(question) + if answer: + print(answer) + else: + print('Нет подходящего ответа данный вопрос') + if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..9a1564a5 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -4,17 +4,22 @@ Исключения: KeyboardInterrupt -* Перепишите функцию hello_user() из задания while1, чтобы она - перехватывала KeyboardInterrupt, писала пользователю "Пока!" +* Перепишите функцию hello_user() из задания while1, чтобы она + перехватывала KeyboardInterrupt, писала пользователю "Пока!" и завершала работу при помощи оператора break - + """ def hello_user(): """ Замените pass на ваш код """ - pass - + try: + answer = '' + while answer != 'Хорошо': + answer = input('Как дела? ') + except KeyboardInterrupt: + print('Пока!') + if __name__ == "__main__": hello_user() From 15b2fe6927c22c9ca3e94161888d93cc153da940 Mon Sep 17 00:00:00 2001 From: kaplya-sys Date: Thu, 8 Sep 2022 14:28:22 +0500 Subject: [PATCH 2/4] completed 8 out of 8 --- 6_exception1.py | 11 ++++++----- 7_exception2.py | 20 ++++++++++++++++---- 8_ephem_bot.py | 16 +++++++++++++++- 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/6_exception1.py b/6_exception1.py index 9a1564a5..a6b5cda3 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -14,12 +14,13 @@ def hello_user(): """ Замените pass на ваш код """ - try: - answer = '' - while answer != 'Хорошо': + answer = '' + while answer != 'Хорошо': + try: answer = input('Как дела? ') - except KeyboardInterrupt: - print('Пока!') + except KeyboardInterrupt: + print('Пока!') + break if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..5804dedc 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -10,15 +10,27 @@ * Первые два нужно приводить к вещественному числу при помощи float(), а третий - к целому при помощи int() и перехватывать исключения ValueError и TypeError, если приведение типов не сработало. - + """ -def discounted(price, discount, max_discount=20) +def discounted(price, discount, max_discount=20): """ Замените pass на ваш код """ - pass - + try: + price = abs(float(price)) + discount = abs(float(discount)) + max_discount = abs(int(max_discount)) + + if max_discount >= 100: + raise ValueError + if discount >= max_discount: + return price + else: + return price - (price * discount / 100) + except (ValueError, TypeError): + print('Ошибка, переданы не верные данные!') + if __name__ == "__main__": print(discounted(100, 2)) print(discounted(100, "3")) diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..f81d78e4 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -16,6 +16,10 @@ from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +from datetime import date + +import ephem + logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO, filename='bot.log') @@ -39,14 +43,24 @@ def greet_user(update, context): def talk_to_me(update, context): user_text = update.message.text print(user_text) - update.message.reply_text(text) + update.message.reply_text(user_text) + +def get_planet_location(update, context): + text_message = update.message.text.split() + date_today = date.today().strftime("%Y/%m/%d") + + fn = getattr(ephem, text_message[1]) + planet = fn(date_today) + constellation = ephem.constellation(planet) + update.message.reply_text(', '.join(constellation)) def main(): mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True) dp = mybot.dispatcher dp.add_handler(CommandHandler("start", greet_user)) + dp.add_handler(CommandHandler("planet", get_planet_location)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) mybot.start_polling() From 925b8c564cefc369dfb8e7c3e5456623c65413f1 Mon Sep 17 00:00:00 2001 From: kaplya-sys Date: Sat, 10 Sep 2022 19:52:01 +0500 Subject: [PATCH 3/4] fixed comments on the second task --- 2_if2.py | 11 +++++------ 3_for.py | 35 +++++------------------------------ 5_while2.py | 4 ++-- 7_exception2.py | 19 +++++++++++-------- 8_ephem_bot.py | 9 ++++++++- 5 files changed, 31 insertions(+), 47 deletions(-) diff --git a/2_if2.py b/2_if2.py index c6c824e4..b9a799bd 100644 --- a/2_if2.py +++ b/2_if2.py @@ -16,15 +16,14 @@ """ def check_string(first_string, second_string): - if type(first_string) and type(second_string) != str: + if isinstance(first_string, str) and isinstance(second_string, str) is not True: return 0 elif first_string == second_string: return 1 - else: - if second_string == 'learn': - return 3 - elif len(first_string) > len(second_string): - return 2 + elif second_string == 'learn': + return 3 + elif len(first_string) > len(second_string): + return 2 def main(): """ diff --git a/3_for.py b/3_for.py index a678bb25..df6adb97 100644 --- a/3_for.py +++ b/3_for.py @@ -22,43 +22,18 @@ {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, ] -def get_total_sold(items_sold): - summ = 0 - for item in items_sold: - summ += item - return summ - -def get_average_sold(items_sold): - summ = 0 - for item in items_sold: - summ += item - return summ / len(items_sold) - def total_sold_each_item(products): - items_summ = [] - for product in products: - item_summ_sold = get_total_sold(product['items_sold']) - items_summ.append({product['product']: item_summ_sold}) - return items_summ + return [{product['product']: sum(product['items_sold'])} for product in products] def total_sold_all_item(products): - all_summ = 0 - for product in products: - all_summ += get_total_sold(product['items_sold']) - return all_summ + return sum([sum(product['items_sold']) for product in products]) def average_sold_each_item(products): - items_summ = [] - for product in products: - item_summ_sold = get_average_sold(product['items_sold']) - items_summ.append({product['product']: item_summ_sold}) - return items_summ + return [{product['product']: sum(product['items_sold']) / len(product['items_sold'])} for product in products] def average_sold_all_item(products): - all_summ = 0 - for product in products: - all_summ += get_average_sold(product['items_sold']) - return all_summ + all_summ = total_sold_all_item(products) + return all_summ / len(sum([product['items_sold'] for product in products], [])) def main(): diff --git a/5_while2.py b/5_while2.py index d1a417e7..2d242484 100644 --- a/5_while2.py +++ b/5_while2.py @@ -29,10 +29,10 @@ def ask_user(answers_dict): while True: question = input('Введите вопрос: ') answer = questions_and_answers.get(question) - if answer: + if not answer is None: print(answer) else: - print('Нет подходящего ответа данный вопрос') + print('Нет подходящего ответа на данный вопроса') if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/7_exception2.py b/7_exception2.py index 5804dedc..9ecd6b02 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -21,15 +21,17 @@ def discounted(price, discount, max_discount=20): price = abs(float(price)) discount = abs(float(discount)) max_discount = abs(int(max_discount)) + except TypeError: + return print('Ошибка, передан не верный тип!') + except ValueError: + return print('Ошибка, переданы не верные данные!') - if max_discount >= 100: - raise ValueError - if discount >= max_discount: - return price - else: - return price - (price * discount / 100) - except (ValueError, TypeError): - print('Ошибка, переданы не верные данные!') + if max_discount >= 100: + raise ValueError('Слишком большая максимальная скидка') + if discount >= max_discount: + return price + else: + return price - (price * discount / 100) if __name__ == "__main__": print(discounted(100, 2)) @@ -38,3 +40,4 @@ def discounted(price, discount, max_discount=20): print(discounted("five", 5)) print(discounted("сто", "десять")) print(discounted(100.0, 5, "10")) + \ No newline at end of file diff --git a/8_ephem_bot.py b/8_ephem_bot.py index f81d78e4..9a38f498 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -49,7 +49,14 @@ def get_planet_location(update, context): text_message = update.message.text.split() date_today = date.today().strftime("%Y/%m/%d") - fn = getattr(ephem, text_message[1]) + if len(text_message) < 2: + return update.message.reply_text('Не указана планета.') + + fn = getattr(ephem, text_message[1], 'err') + + if fn == 'err': + return update.message.reply_text('Допущена ошибка вводе планеты.') + planet = fn(date_today) constellation = ephem.constellation(planet) From 37794521dad784b2e4afef549ded47fe9440466a Mon Sep 17 00:00:00 2001 From: kaplya-sys Date: Sun, 11 Sep 2022 19:30:24 +0500 Subject: [PATCH 4/4] added fix 1, 2, 5, 7, 8 files --- 1_if1.py | 18 ++++++++++++------ 2_if2.py | 2 +- 5_while2.py | 2 +- 7_exception2.py | 7 ++++--- 8_ephem_bot.py | 6 +++--- 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/1_if1.py b/1_if1.py index 72718d1f..108ae92c 100644 --- a/1_if1.py +++ b/1_if1.py @@ -15,17 +15,23 @@ """ def distribute_career(age): if age < 1.5: - return print('Ты совсем еще маленький') + print('Ты совсем еще маленький') + return elif 1.5 <= age <= 7: - return print('Ходить в детский сад') + print('Ходить в детский сад') + return elif 7 < age <= 18: - return print('Учиться в школе') + print('Учиться в школе') + return elif 18 < age <= 23: - return print('Учиться в ВУЗе') + print('Учиться в ВУЗе') + return elif 23 < age <= 70: - return print('Пора работать') + print('Пора работать') + return else: - return print('Пора уже на пенсию') + print('Пора уже на пенсию') + return def main(): diff --git a/2_if2.py b/2_if2.py index b9a799bd..79e1b8f0 100644 --- a/2_if2.py +++ b/2_if2.py @@ -16,7 +16,7 @@ """ def check_string(first_string, second_string): - if isinstance(first_string, str) and isinstance(second_string, str) is not True: + if not isinstance(first_string, str) or not isinstance(second_string, str): return 0 elif first_string == second_string: return 1 diff --git a/5_while2.py b/5_while2.py index 2d242484..a4e62e87 100644 --- a/5_while2.py +++ b/5_while2.py @@ -29,7 +29,7 @@ def ask_user(answers_dict): while True: question = input('Введите вопрос: ') answer = questions_and_answers.get(question) - if not answer is None: + if answer is not None: print(answer) else: print('Нет подходящего ответа на данный вопроса') diff --git a/7_exception2.py b/7_exception2.py index 9ecd6b02..cded39b0 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -22,9 +22,11 @@ def discounted(price, discount, max_discount=20): discount = abs(float(discount)) max_discount = abs(int(max_discount)) except TypeError: - return print('Ошибка, передан не верный тип!') + print('Ошибка, передан не верный тип!') + return except ValueError: - return print('Ошибка, переданы не верные данные!') + print('Ошибка, переданы не верные данные!') + return if max_discount >= 100: raise ValueError('Слишком большая максимальная скидка') @@ -40,4 +42,3 @@ def discounted(price, discount, max_discount=20): print(discounted("five", 5)) print(discounted("сто", "десять")) print(discounted(100.0, 5, "10")) - \ No newline at end of file diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 9a38f498..bf7d7c1c 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -52,12 +52,12 @@ def get_planet_location(update, context): if len(text_message) < 2: return update.message.reply_text('Не указана планета.') - fn = getattr(ephem, text_message[1], 'err') + get_attribute = getattr(ephem, text_message[1], None) - if fn == 'err': + if get_attribute is None: return update.message.reply_text('Допущена ошибка вводе планеты.') - planet = fn(date_today) + planet = get_attribute(date_today) constellation = ephem.constellation(planet) update.message.reply_text(', '.join(constellation))