From 517797896042ce28a9eb3cd23cfdc9094d5ad030 Mon Sep 17 00:00:00 2001 From: AlexandraPoturaeva Date: Tue, 16 May 2023 12:58:22 +0300 Subject: [PATCH 1/5] ex. 1 and 2 --- .gitignore | 2 ++ 1_if1.py | 34 ++++++++++++++++++++++++++++++---- 2_if2.py | 29 +++++++++++++++++++++-------- 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index af6d5026..eb681a4f 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,5 @@ dmypy.json # Pyre type checker .pyre/ + +.idea/ diff --git a/1_if1.py b/1_if1.py index be736084..507a1403 100644 --- a/1_if1.py +++ b/1_if1.py @@ -4,22 +4,48 @@ Условный оператор: Возраст -* Попросить пользователя ввести возраст при помощи input и положить +* Попросить пользователя ввести возраст при помощи input и положить результат в переменную -* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: +* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать -* Вызвать функцию, передав ей возраст пользователя и положить результат +* Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в переменную * Вывести содержимое переменной на экран """ +from typing import Optional + + +def define_occupation_by_age(age: int) -> Optional[str]: + """ + Function get user age and define their expected occupation + """ + if 0 <= age < 7: + return 'учиться в детском саду' + elif 7 <= age < 17: + return 'учиться в школе' + elif 17 <= age < 24: + return 'учиться в ВУЗе' + elif 24 <= age < 65: + return 'работать' + elif 65 <= age <= 120: + return 'отдыхать (быть пенсионером)' + + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + while True: + user_age = int(input('Введите возраст (от 0 до 120 лет): ')) + if user_age < 0 or user_age > 120: + print('Возраст введён некорректно, попробуйте ещё раз') + else: + user_expected_occupation = define_occupation_by_age(user_age) + print(f'Ожидается, что в этом возрасте человек должен {user_expected_occupation}') + if __name__ == "__main__": main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..af70e142 100644 --- a/2_if2.py +++ b/2_if2.py @@ -5,22 +5,35 @@ Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки -* Проверить, является ли то, что передано функции, строками. +* Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 -* Вызвать функцию несколько раз, передавая ей разные праметры +* Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ + +def compare_strings(string_1: str, string_2: str) -> int: + if not all([isinstance(string_1, str), isinstance(string_2, str)]): + return 0 + elif string_1 == string_2: + return 1 + elif len(string_1) > len(string_2) and string_2 != 'learn': + return 2 + elif string_1 != string_2 and string_2 == 'learn': + return 3 + + def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - + print(compare_strings(1, 'string')) + print(compare_strings('string', 'string')) + print(compare_strings('strings', 'string')) + print(compare_strings('string', 'learn')) + print(compare_strings('learn', 'string')) + + if __name__ == "__main__": main() From 9142b2499e128756a5209fe190f25e4c27050a3b Mon Sep 17 00:00:00 2001 From: AlexandraPoturaeva Date: Wed, 17 May 2023 11:45:55 +0300 Subject: [PATCH 2/5] ex. 3 --- 3_for.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/3_for.py b/3_for.py index 5ca9f504..21db5c31 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,36 @@ * Посчитать и вывести среднее количество продаж всех товаров """ +sales_info = [ + {'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 main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + total_sales = 0 + total_sale_times = 0 + + print('1-2. Суммарное/среднее количество продаж по товарам:') + for product in sales_info: + total_product_sales = sum(product["items_sold"]) + total_product_sale_times = len(product["items_sold"]) + avg_product_sales = round(total_product_sales/total_product_sale_times) + + total_sales += total_product_sales + total_sale_times += total_product_sale_times + + print(f'\t{product["product"]} - {total_product_sales}/{avg_product_sales}') + + print(f'\n3. Cуммарное количество продаж всех товаров: {total_sales}') + + print(f'\n4. Cреднее количество продаж всех товаров: {round(total_sales/total_sale_times)}') + + if __name__ == "__main__": main() From 5c1af09e2d174f42edfcbe9da0c5b34529380453 Mon Sep 17 00:00:00 2001 From: AlexandraPoturaeva Date: Wed, 17 May 2023 16:23:10 +0300 Subject: [PATCH 3/5] ex. 4-8 --- .gitignore | 2 ++ 4_while1.py | 14 ++++++------- 5_while2.py | 21 ++++++++++++------- 6_exception1.py | 21 ++++++++++++------- 7_exception2.py | 33 ++++++++++++++++++++++------- 8_ephem_bot.py | 56 +++++++++++++++++++++++++++++++++---------------- 6 files changed, 100 insertions(+), 47 deletions(-) diff --git a/.gitignore b/.gitignore index eb681a4f..df14a164 100644 --- a/.gitignore +++ b/.gitignore @@ -123,3 +123,5 @@ dmypy.json .pyre/ .idea/ +settings.py + diff --git a/4_while1.py b/4_while1.py index b5791517..3c3b9a9f 100644 --- a/4_while1.py +++ b/4_while1.py @@ -4,18 +4,18 @@ Цикл while: hello_user -* Напишите функцию hello_user(), которая с помощью функции input() спрашивает +* Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” - + """ def hello_user(): - """ - Замените pass на ваш код - """ - pass + while True: + user_response = input('Как дела? ') + if user_response == 'Хорошо': + break + - if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..5dfe1807 100644 --- a/5_while2.py +++ b/5_while2.py @@ -12,16 +12,23 @@ Пользователь: Что делаешь? Программа: Программирую - + """ +import datetime + +questions_and_answers = { + 'Как дела?': 'Хорошо!', + 'Что делаешь?': 'Программирую', + 'Пойдём гулять?': 'Пойдём', + 'Сколько время?': datetime.datetime.now() +} -questions_and_answers = {} def ask_user(answers_dict): - """ - Замените pass на ваш код - """ - pass - + while True: + user_question = input('Введите вопрос: ') + print(answers_dict.get(user_question, 'не знаю')) + + if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..50f83f6c 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: + while True: + user_response = input('Как дела? ') + if user_response == 'Хорошо': + break + except KeyboardInterrupt: + print('\nПока') + + if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..f60cfb5c 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -10,15 +10,34 @@ * Первые два нужно приводить к вещественному числу при помощи float(), а третий - к целому при помощи int() и перехватывать исключения ValueError и TypeError, если приведение типов не сработало. - + """ +import traceback + + +def discounted(price, discount, max_discount=20): + try: + price = float(price) + discount = float(discount) + max_discount = int(max_discount) + if max_discount >= 100: + raise Exception('Слишком большая максимальная скидка') + if discount >= max_discount: + return price + else: + return price - (price * discount / 100) + except ValueError: + traceback_split = traceback.format_exc().split() + for var in discounted.__code__.co_varnames[:2]: + if var in traceback_split: + return f'Неверное значение переменной {var}' + except TypeError: + traceback_split = traceback.format_exc().split() + for var in discounted.__code__.co_varnames[:2]: + if var in traceback_split: + return f'Неверный тип переменной {var}' + -def discounted(price, discount, max_discount=20) - """ - Замените pass на ваш код - """ - pass - 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..ba042c97 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -13,42 +13,62 @@ """ import logging +import time +from datetime import date +import settings +import ephem from telegram.ext import Updater, CommandHandler, MessageHandler, Filters -logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', - level=logging.INFO, - filename='bot.log') +logging.Formatter.converter = time.gmtime +logging.basicConfig( + filename='bot.log', + level=logging.INFO, + datefmt='%d.%m.%Y %H:%M:%S', + format='%(asctime)s (GMT+0) %(message)s', + encoding='utf-8' +) -PROXY = { - 'proxy_url': 'socks5://t1.learn.python.ru:1080', - 'urllib3_proxy_kwargs': { - 'username': 'learn', - 'password': 'python' - } -} +def greet_user(update, context): + print('Вызван /start') + update.message.reply_text('Здравствуй, пользователь!') -def greet_user(update, context): - text = 'Вызван /start' +def talk_to_me(update, context): + text = update.message.text print(text) update.message.reply_text(text) -def talk_to_me(update, context): - user_text = update.message.text - print(user_text) - update.message.reply_text(text) +def check_current_planet_constellation(update, context): + current_date = date.today() + ephem_planets = { + 'mars': ephem.Mars, + 'mercury': ephem.Mercury, + 'venus': ephem.Venus, + 'jupiter': ephem.Jupiter, + 'saturn': ephem.Saturn, + 'uranus': ephem.Uranus, + 'neptune': ephem.Neptune + } + planet = update.message.text.split()[1].lower() + + if planet in ephem_planets: + update.message.reply_text( + f'Today {planet.capitalize()} is in {ephem.constellation(ephem_planets[planet](current_date))}' + ) 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', check_current_planet_constellation)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) + logging.info('Бот стартовал') mybot.start_polling() mybot.idle() From abc65abbdec0bfff3e2905045f5dd3ed13438168 Mon Sep 17 00:00:00 2001 From: AlexandraPoturaeva Date: Mon, 22 May 2023 10:42:20 +0300 Subject: [PATCH 4/5] corrections made --- 1_if1.py | 4 +--- 2_if2.py | 2 +- 3_for.py | 47 ++++++++++++++++++++++++++++++++--------------- 7_exception2.py | 42 ++++++++++++++++++++++++++++++++++++------ 4 files changed, 70 insertions(+), 25 deletions(-) diff --git a/1_if1.py b/1_if1.py index 507a1403..1ab9bf78 100644 --- a/1_if1.py +++ b/1_if1.py @@ -14,10 +14,8 @@ """ -from typing import Optional - -def define_occupation_by_age(age: int) -> Optional[str]: +def define_occupation_by_age(age: int) -> str: """ Function get user age and define their expected occupation """ diff --git a/2_if2.py b/2_if2.py index af70e142..6e193ade 100644 --- a/2_if2.py +++ b/2_if2.py @@ -17,7 +17,7 @@ def compare_strings(string_1: str, string_2: str) -> int: - if not all([isinstance(string_1, str), isinstance(string_2, str)]): + if not isinstance(string_1, str) or not isinstance(string_2, str): return 0 elif string_1 == string_2: return 1 diff --git a/3_for.py b/3_for.py index 21db5c31..2e7f391d 100644 --- a/3_for.py +++ b/3_for.py @@ -16,11 +16,32 @@ * Посчитать и вывести среднее количество продаж всех товаров """ -sales_info = [ +sales = [ {'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 product_sales(product): + return sum(product["items_sold"]) + + +def product_sale_times(product): + return len(product["items_sold"]) + + +def total_sales(sales_dict): + return sum([product_sales(product) for product in sales_dict]) + + +def total_sale_times(sales_dict): + total_sales_times = sum([product_sale_times(product) for product in sales_dict]) + return total_sales_times + + +def avg_sale(sales, sale_times): + return round(sales/sale_times) def main(): @@ -28,23 +49,19 @@ def main(): Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - total_sales = 0 - total_sale_times = 0 - - print('1-2. Суммарное/среднее количество продаж по товарам:') - for product in sales_info: - total_product_sales = sum(product["items_sold"]) - total_product_sale_times = len(product["items_sold"]) - avg_product_sales = round(total_product_sales/total_product_sale_times) - total_sales += total_product_sales - total_sale_times += total_product_sale_times + print('1. Суммарное количество продаж по товарам:') + for product in sales: + print(f'\t{product["product"]}: {product_sales(product)}') - print(f'\t{product["product"]} - {total_product_sales}/{avg_product_sales}') + print('\n2. Среднее количество продаж по товарам:') + for product in sales: + print(f'\t{product["product"]}: {avg_sale(product_sales(product), product_sale_times(product))}') - print(f'\n3. Cуммарное количество продаж всех товаров: {total_sales}') + print(f'\n3. Cуммарное количество продаж всех товаров: {total_sales(sales)}') - print(f'\n4. Cреднее количество продаж всех товаров: {round(total_sales/total_sale_times)}') + print(f'\n4. Cреднее количество продаж всех товаров: ' + f'{avg_sale(total_sales(sales), total_sale_times(sales))}') if __name__ == "__main__": diff --git a/7_exception2.py b/7_exception2.py index f60cfb5c..461cae35 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -15,17 +15,12 @@ import traceback +# Вариант 1 (получение информации о переменной, которая передана неверно, из traceback) def discounted(price, discount, max_discount=20): try: price = float(price) discount = float(discount) max_discount = int(max_discount) - if max_discount >= 100: - raise Exception('Слишком большая максимальная скидка') - if discount >= max_discount: - return price - else: - return price - (price * discount / 100) except ValueError: traceback_split = traceback.format_exc().split() for var in discounted.__code__.co_varnames[:2]: @@ -37,6 +32,41 @@ def discounted(price, discount, max_discount=20): if var in traceback_split: return f'Неверный тип переменной {var}' + if max_discount >= 100: + raise ValueError('Слишком большая максимальная скидка') + if discount >= max_discount: + return price + else: + return price - (price * discount / 100) + + +# Вариант 2 (как надо делать) +def discounted(price, discount, max_discount=20): + error_message = 'Неверное значение переменной' + expected_exceptions = (ValueError, TypeError) + + try: + price = float(price) + except expected_exceptions: + return f'{error_message} price' + + try: + discount = float(discount) + except expected_exceptions: + return f'{error_message} discount' + + try: + max_discount = int(max_discount) + except expected_exceptions: + return f'{error_message} max_discount' + + 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)) From 7a1b7c940fb2140ea5c628888c2b60b9b175d2d0 Mon Sep 17 00:00:00 2001 From: AlexandraPoturaeva Date: Fri, 26 May 2023 16:36:01 +0300 Subject: [PATCH 5/5] corrections made --- 1_if1.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1_if1.py b/1_if1.py index 1ab9bf78..d291beb2 100644 --- a/1_if1.py +++ b/1_if1.py @@ -19,7 +19,7 @@ def define_occupation_by_age(age: int) -> str: """ Function get user age and define their expected occupation """ - if 0 <= age < 7: + if age < 7: return 'учиться в детском саду' elif 7 <= age < 17: return 'учиться в школе' @@ -27,7 +27,7 @@ def define_occupation_by_age(age: int) -> str: return 'учиться в ВУЗе' elif 24 <= age < 65: return 'работать' - elif 65 <= age <= 120: + elif 65 <= age: return 'отдыхать (быть пенсионером)'