diff --git a/.gitignore b/.gitignore index af6d5026..df14a164 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,7 @@ dmypy.json # Pyre type checker .pyre/ + +.idea/ +settings.py + diff --git a/1_if1.py b/1_if1.py index be736084..d291beb2 100644 --- a/1_if1.py +++ b/1_if1.py @@ -4,22 +4,46 @@ Условный оператор: Возраст -* Попросить пользователя ввести возраст при помощи input и положить +* Попросить пользователя ввести возраст при помощи input и положить результат в переменную -* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: +* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать -* Вызвать функцию, передав ей возраст пользователя и положить результат +* Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в переменную * Вывести содержимое переменной на экран """ + +def define_occupation_by_age(age: int) -> str: + """ + Function get user age and define their expected occupation + """ + if age < 7: + return 'учиться в детском саду' + elif 7 <= age < 17: + return 'учиться в школе' + elif 17 <= age < 24: + return 'учиться в ВУЗе' + elif 24 <= age < 65: + return 'работать' + elif 65 <= age: + 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..6e193ade 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 isinstance(string_1, str) or not 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() diff --git a/3_for.py b/3_for.py index 5ca9f504..2e7f391d 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,53 @@ * Посчитать и вывести среднее количество продаж всех товаров """ +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(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + + print('1. Суммарное количество продаж по товарам:') + for product in sales: + print(f'\t{product["product"]}: {product_sales(product)}') + + 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(sales)}') + + print(f'\n4. Cреднее количество продаж всех товаров: ' + f'{avg_sale(total_sales(sales), total_sale_times(sales))}') + + if __name__ == "__main__": main() 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..461cae35 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -10,15 +10,64 @@ * Первые два нужно приводить к вещественному числу при помощи float(), а третий - к целому при помощи int() и перехватывать исключения ValueError и TypeError, если приведение типов не сработало. - + """ +import traceback + + +# Вариант 1 (получение информации о переменной, которая передана неверно, из traceback) +def discounted(price, discount, max_discount=20): + try: + price = float(price) + discount = float(discount) + max_discount = int(max_discount) + 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}' + + 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) + -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()