diff --git a/.gitignore b/.gitignore index af6d5026..358f2c9c 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,6 @@ dmypy.json # Pyre type checker .pyre/ + +# Settings +settings.py \ No newline at end of file diff --git a/1_if1.py b/1_if1.py index be736084..48d5ab8d 100644 --- a/1_if1.py +++ b/1_if1.py @@ -14,12 +14,16 @@ """ -def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass + +def activity_by_age(age): + if age <= 7: + return 'Вы в детском садике' + elif age <= 17: + return 'Вы учитесь в школе' + else: + return 'Вы в ВУЗе или работаете' + if __name__ == "__main__": - main() + age = abs(int(input('Введите ваш возраст: '))) + print(activity_by_age(age)) diff --git a/2_if2.py b/2_if2.py index 0f1644f3..8223b137 100644 --- a/2_if2.py +++ b/2_if2.py @@ -15,12 +15,36 @@ """ + +def check_strings(str1, str2): + if not isinstance(str1, str) or not isinstance(str2, str): + return 0 + + str1 = str1.strip().lower() + str2 = str2.strip().lower() + + if str1 == str2: + return 1 + elif str2 == 'learn': + return 3 + elif len(str1) > len(str2): + return 2 + else: + return 'Вот это поворот' + + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + + print(check_strings('hello', 777)) # 0 + print(check_strings('hello', 'hello')) # 1 + print(check_strings('hello', 'hell')) # 2 + print(check_strings('hi', 'learn')) # 3 + print(check_strings('hi', 'learning')) + + if __name__ == "__main__": main() diff --git a/3_for.py b/3_for.py index 5ca9f504..125cd166 100644 --- a/3_for.py +++ b/3_for.py @@ -16,12 +16,41 @@ * Посчитать и вывести среднее количество продаж всех товаров """ + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - + + 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 count_sum(items_list): + items_sum = 0 + for item in items_list: + items_sum += item + return items_sum + + phones_sum = 0 + for phone in phones: + phone['sum_sold'] = count_sum(phone['items_sold']) + phone_sold_avg = int(phone['sum_sold'] / len(phone['items_sold'])) + phones_sum += phone['sum_sold'] + print( + f"Суммарный объем продаж {phone['product']}: {phone['sum_sold']}") + print( + f"Средний объем продаж {phone['product']}: {phone_sold_avg}", end='\n\n') + print(f"Всего телефонов продано: {phones_sum}") + phones_avg = int(phones_sum / len(phones)) + print(f"В среднем телефонов продано: {phones_avg}") + + if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..35a78ef9 100644 --- a/4_while1.py +++ b/4_while1.py @@ -14,8 +14,10 @@ def hello_user(): """ Замените pass на ваш код """ - pass + while True: + if input('Как дела? \n') == 'Хорошо': + break + - if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..ea81df32 100644 --- a/5_while2.py +++ b/5_while2.py @@ -15,13 +15,22 @@ """ -questions_and_answers = {} +questions_and_answers = { + 'Как дела': 'Хорошо!', + 'Что делаешь': 'Программирую', + 'И все?': 'Ну, почти', + 'Ну и лошара': 'Да пошел ты' +} def ask_user(answers_dict): """ Замените pass на ваш код """ - pass + print('Введите вопрос: ') + while True: + question = input('Пользователь: ') + if answers_dict.get(question): + print(f"Программа: {answers_dict.get(question, '')}", end='\n\n') if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..443778c4 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -14,7 +14,12 @@ def hello_user(): """ Замените pass на ваш код """ - pass + try: + while True: + if input('Как дела? \n') == 'Хорошо': + break + except KeyboardInterrupt: + print('Пока') if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..37de7d6b 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -13,16 +13,35 @@ """ -def discounted(price, discount, max_discount=20) +def discounted(price, discount, max_discount=20): """ Замените pass на ваш код """ - pass + + try: + price = abs(float(price)) + except (ValueError, TypeError): + return 'Цена должна быть числом' + try: + discount = abs(float(discount)) + except (ValueError, TypeError): + return 'Размер скидки должен быть числом' + try: + max_discount = abs(int(max_discount)) + except (ValueError, TypeError): + return 'Максимальная скидка должна быть числом' + + 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)) - print(discounted(100, "3")) - print(discounted("100", "4.5")) - print(discounted("five", 5)) - print(discounted("сто", "десять")) - print(discounted(100.0, 5, "10")) + print("---", discounted(100, 2)) + print("---", discounted(100, "3")) + print("---", discounted("100", "4.5")) + print("---", discounted("five", 5)) + print("---", discounted("сто", "десять")) + print("---", discounted(100.0, 5, "10")) diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..bd51c116 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -14,20 +14,22 @@ """ import logging +import ephem, pprint from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +import settings 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' - } -} +# PROXY = { +# 'proxy_url': 'socks5://t1.learn.python.ru:1080', +# 'urllib3_proxy_kwargs': { +# 'username': 'learn', +# 'password': 'python' +# } +# } def greet_user(update, context): @@ -39,14 +41,45 @@ 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) + +planet_name = { + 'Mercury': ephem.Mercury(), + 'Venus': ephem.Venus(), + 'Mars': ephem.Mars(), + 'Jupiter': ephem.Jupiter(), + 'Saturn': ephem.Saturn(), + 'Uranus': ephem.Uranus(), + 'Neptune': ephem.Neptune(), + 'Pluto': ephem.Pluto() + } + +def get_constellation(update, context): + user_input = context.args[0].capitalize() + + try: + planet_name[user_input] + except KeyError: + if user_input == 'Earth': + update.message.reply_text('Earth is not in any constellation') + else: + update.message.reply_text(f'{user_input} is not a planet of solar system') + + planet_name[user_input].compute() + constellation_name = ephem.constellation(planet_name[user_input])[1] + # print(constellation_name, constellation_name[1]) + # constellation_name = update.message.text.split() + print(f'{planet_name[user_input].name} is currently in the constellation of {constellation_name}') + update.message.reply_text(f'{planet_name[user_input].name} is currently in the constellation of {constellation_name}') + 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("planet", get_constellation)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) mybot.start_polling()