From 0b3149b4a1d7e47c2a2a73c66f5dd16311d8ce7b Mon Sep 17 00:00:00 2001 From: Prokhorov Mark Date: Thu, 16 Feb 2023 21:46:11 +0300 Subject: [PATCH 1/3] finished work --- 1_if1.py | 21 ++++++++++++------- 2_if2.py | 29 ++++++++++++++++++++++--- 3_for.py | 29 ++++++++++++++++++------- 4_while1.py | 11 +++++----- 5_while2.py | 13 +++++++----- 6_exception1.py | 11 ++++++---- 7_exception2.py | 18 +++++++++++----- 8_ephem_bot.py | 56 ++++++++++++++++--------------------------------- 8 files changed, 112 insertions(+), 76 deletions(-) diff --git a/1_if1.py b/1_if1.py index be736084..abd3add7 100644 --- a/1_if1.py +++ b/1_if1.py @@ -14,12 +14,19 @@ """ -def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass +def main(age): + if age < 7: + return "Вы должны быть в детском саду" + elif 7 <= age < 18: + return "Вы должны учиться в школе" + elif 18 <= age < 22: + return "Вы должны учиться в ВУЗе" + else: + return "Вы должны работать" + +age = int(input("Введите возраст: ")) +what_to_do = main(age) +print(what_to_do) if __name__ == "__main__": - main() + main(age) diff --git a/2_if2.py b/2_if2.py index 0f1644f3..b1b96d5d 100644 --- a/2_if2.py +++ b/2_if2.py @@ -15,12 +15,35 @@ """ -def main(): +def main(str_1, str_2): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + if isinstance(str_1, str) and isinstance(str_2, str): + if str_1 == str_2: + return 1 + elif str_2 == "learn": + return 3 + elif len(str_1) > len(str_2): + return 2 + else: + return 0 + +str_1, str_2 = '123', 2 +print(main(str_1, str_2)) + +str_1, str_2 = '123', '123' +print(main(str_1, str_2)) + +str_1, str_2 = '123', '2' +print(main(str_1, str_2)) + +str_1, str_2 = '123', 'learn' +print(main(str_1, str_2)) + +str_1, str_2 = '123', '1234' +print(main(str_1, str_2)) if __name__ == "__main__": - main() + main(str_1, str_2) diff --git a/3_for.py b/3_for.py index 5ca9f504..b14b4862 100644 --- a/3_for.py +++ b/3_for.py @@ -16,12 +16,25 @@ * Посчитать и вывести среднее количество продаж всех товаров """ -def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - +def main(sales_figures): + total_sales = average_sales = 0 + for i in sales_figures: + phone = i['product'] + t_sale = a_sale = 0 + for sale in i['items_sold']: + t_sale += sale + a_sale += 1 + total_sales += sale + average_sales += 1 + print(f'суммарное количество продаж {phone}: {total_sales}, среднее количество продаж {phone}: {total_sales // average_sales}') + print(f'суммарное количество продаж всех товаров: {total_sales}, среднее количество продаж всех товаров: {total_sales // average_sales}') + +sales_figures = [ + {'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]}, + ] + + if __name__ == "__main__": - main() + main(sales_figures) \ No newline at end of file diff --git a/4_while1.py b/4_while1.py index b5791517..2eda8d76 100644 --- a/4_while1.py +++ b/4_while1.py @@ -11,11 +11,10 @@ def hello_user(): - """ - Замените pass на ваш код - """ - pass - - + while True: + user_say = input('Как дела? ') + if user_say == 'Хорошо': + break + if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..492a5d7b 100644 --- a/5_while2.py +++ b/5_while2.py @@ -15,13 +15,16 @@ """ -questions_and_answers = {} +questions_and_answers = {"Как дела?": "Хорошо!", + "Что делаешь?": "Программирую" + +} def ask_user(answers_dict): - """ - Замените pass на ваш код - """ - pass + while True: + user_say = input("Введите вопрос: ") + if user_say in questions_and_answers: + print(f'Программа: {questions_and_answers[user_say]}') if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..68a74540 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -11,10 +11,13 @@ """ def hello_user(): - """ - Замените pass на ваш код - """ - pass + try: + while True: + user_say = input('Как дела?\n') + if user_say == 'Хорошо': + break + except KeyboardInterrupt: + print('Пока!') if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..96c58a63 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -13,11 +13,19 @@ """ -def discounted(price, discount, max_discount=20) - """ - Замените pass на ваш код - """ - pass +def discounted(price, discount, max_discount=20): + 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)) diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..9c493933 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -1,57 +1,37 @@ -""" -Домашнее задание №1 - -Использование библиотек: ephem - -* Установите модуль ephem -* Добавьте в бота команду /planet, которая будет принимать на вход - название планеты на английском, например /planet Mars -* В функции-обработчике команды из update.message.text получите - название планеты (подсказка: используйте .split()) -* При помощи условного оператора if и ephem.constellation научите - бота отвечать, в каком созвездии сегодня находится планета. - -""" import logging - +import ephem +from datetime import date from telegram.ext import Updater, CommandHandler, MessageHandler, Filters -logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', - level=logging.INFO, - filename='bot.log') - - -PROXY = { - 'proxy_url': 'socks5://t1.learn.python.ru:1080', - 'urllib3_proxy_kwargs': { - 'username': 'learn', - 'password': 'python' - } -} +import settings +logging.basicConfig(filename='bot.log', level=logging.INFO) def greet_user(update, context): - text = 'Вызван /start' - print(text) - update.message.reply_text(text) - + update.message.reply_text('Здравствуй пользователь!') def talk_to_me(update, context): - user_text = update.message.text - print(user_text) + text = update.message.text update.message.reply_text(text) +def planetary_constellation(update, context): + current_date = date.today() + planet_name = update.message.text.split()[-1].capitalize() + planet = getattr(ephem, planet_name)(current_date) + constellation = ephem.constellation(planet) + update.message.reply_text(f'Планета {planet_name} находиться в созвездии: {constellation[-1]}') def main(): - mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True) + mybot = Updater(settings.API_KEY, use_context=True) dp = mybot.dispatcher - dp.add_handler(CommandHandler("start", greet_user)) + dp.add_handler(CommandHandler('start', greet_user)) + dp.add_handler(CommandHandler('planet', planetary_constellation)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) + logging.info('bot started') mybot.start_polling() mybot.idle() - -if __name__ == "__main__": - main() +if __name__ == '__main__': + main() \ No newline at end of file From e1be9a417a642239ddc1b02145741173020eba74 Mon Sep 17 00:00:00 2001 From: Prokhorov Mark Date: Fri, 17 Feb 2023 21:13:06 +0300 Subject: [PATCH 2/3] =?UTF-8?q?=D1=8Bmall=20tweaks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 1_if1.py | 2 -- 7_exception2.py | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/1_if1.py b/1_if1.py index abd3add7..3f623782 100644 --- a/1_if1.py +++ b/1_if1.py @@ -25,8 +25,6 @@ def main(age): return "Вы должны работать" age = int(input("Введите возраст: ")) -what_to_do = main(age) -print(what_to_do) if __name__ == "__main__": main(age) diff --git a/7_exception2.py b/7_exception2.py index 96c58a63..a68c0a0c 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -25,7 +25,7 @@ def discounted(price, discount, max_discount=20): else: return price - (price * discount / 100) except (ValueError, TypeError): - print('Некорректные аргументы') + return 'Некорректные аргументы' if __name__ == "__main__": print(discounted(100, 2)) From 9ccb73e905c9d618838252be51a7590a9725b05a Mon Sep 17 00:00:00 2001 From: Prokhorov Mark Date: Fri, 24 Feb 2023 14:52:18 +0300 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B4=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2_if2.py | 3 +-- 3_for.py | 47 ++++++++++++++++++++++++++++++----------------- 7_exception2.py | 2 +- 3 files changed, 32 insertions(+), 20 deletions(-) diff --git a/2_if2.py b/2_if2.py index b1b96d5d..d2c518f5 100644 --- a/2_if2.py +++ b/2_if2.py @@ -27,8 +27,7 @@ def main(str_1, str_2): return 3 elif len(str_1) > len(str_2): return 2 - else: - return 0 + return 0 str_1, str_2 = '123', 2 print(main(str_1, str_2)) diff --git a/3_for.py b/3_for.py index b14b4862..de2bfcca 100644 --- a/3_for.py +++ b/3_for.py @@ -15,26 +15,39 @@ * Посчитать и вывести суммарное количество продаж всех товаров * Посчитать и вывести среднее количество продаж всех товаров """ +def phone_sales_amount(items_sold): + total_sales, number_of_sales = 0, 0 + for sale in items_sold: + total_sales += sale + number_of_sales += 1 + average_sales = total_sales // number_of_sales + return total_sales, average_sales +def total_number_of_sales_for_each_product(phone, total_sales): + return f'Всего продаж {phone}: {total_sales}' +def average_number_of_sales_for_each_product(phone, average_sales): + return f'Средние количетсво продаж {phone}: {average_sales}' +def total_and_average_number_of_phone_sales(sales_figures): + total_sales, number_of_sales = 0, 0 + for dict in sales_figures: + total_sales += phone_sales_amount(dict['items_sold'])[0] + number_of_sales += 1 + average_number_of_phone_sales = total_sales // number_of_sales + return total_sales, average_number_of_phone_sales -def main(sales_figures): - total_sales = average_sales = 0 - for i in sales_figures: - phone = i['product'] - t_sale = a_sale = 0 - for sale in i['items_sold']: - t_sale += sale - a_sale += 1 - total_sales += sale - average_sales += 1 - print(f'суммарное количество продаж {phone}: {total_sales}, среднее количество продаж {phone}: {total_sales // average_sales}') - print(f'суммарное количество продаж всех товаров: {total_sales}, среднее количество продаж всех товаров: {total_sales // average_sales}') -sales_figures = [ +if __name__ == "__main__": + sales_figures = [ {'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]}, ] - - -if __name__ == "__main__": - main(sales_figures) \ No newline at end of file + for dict in sales_figures: + phone = dict['product'] + total_sales = phone_sales_amount(dict['items_sold'])[0] + print(total_number_of_sales_for_each_product(phone, total_sales)) + for dict in sales_figures: + phone = dict['product'] + average_sales = phone_sales_amount(dict['items_sold'])[1] + print(average_number_of_sales_for_each_product(phone, average_sales)) + print(f'Сумммарное количество продаж всех товаров: {total_and_average_number_of_phone_sales(sales_figures)[0]}') + print(f'Средние количество продаж всех товаров: {total_and_average_number_of_phone_sales(sales_figures)[1]}') \ No newline at end of file diff --git a/7_exception2.py b/7_exception2.py index a68c0a0c..04a3176d 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -20,7 +20,7 @@ def discounted(price, discount, max_discount=20): max_discount = abs(int(max_discount)) if max_discount >= 100: raise ValueError('Слишком большая максимальная скидка') - if discount >= max_discount: + if discount > max_discount: return price else: return price - (price * discount / 100)