diff --git a/.gitignore b/.gitignore index af6d5026..32d3f728 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,5 @@ dmypy.json # Pyre type checker .pyre/ + +settings.py diff --git a/1_if1.py b/1_if1.py index be736084..ba720083 100644 --- a/1_if1.py +++ b/1_if1.py @@ -4,22 +4,37 @@ Условный оператор: Возраст -* Попросить пользователя ввести возраст при помощи input и положить +* Попросить пользователя ввести возраст при помощи input и положить результат в переменную -* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: +* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать -* Вызвать функцию, передав ей возраст пользователя и положить результат +* Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в переменную * Вывести содержимое переменной на экран """ + def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + + def you_need(your_age): + if 1 <= your_age < 6: + return 'Вам нужно учиться в детском саду' + elif 6 <= your_age < 18: + return 'Вам нужно учиться в школе' + elif 18 <= your_age < 21: + return 'Вам нужно учиться в ВУЗе' + elif 21 <= your_age < 80: + return 'Вам нужно работать' + else: + return 'Вам нужно отдыхать' + + print(you_need(int(input('Введите ваш возраст: \n')))) + if __name__ == "__main__": main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..404ad2cf 100644 --- a/2_if2.py +++ b/2_if2.py @@ -5,22 +5,37 @@ Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки -* Проверить, является ли то, что передано функции, строками. +* Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 -* Вызвать функцию несколько раз, передавая ей разные праметры +* Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ + +def strings(str1, str2): + if not isinstance(str1, str) or not isinstance(str2, str): + return 0 + elif str1 == str2: + return 1 + elif len(str1) > len(str2) and str2 != 'learn': + return 2 + elif str2.lower() == 'learn': + return 3 + return f'Для строк "{str1}" и "{str2}" нет вывода' + + def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - + print(strings('hello', 1)) + print(strings('hello', 'world')) + print(strings('qwerty', '123')) + print(strings('learn', 'learn')) + print(strings('learn_python', 'learn')) + print(strings(None, None)) + + if __name__ == "__main__": main() diff --git a/3_for.py b/3_for.py index 5ca9f504..b5bc8503 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,41 @@ * Посчитать и вывести среднее количество продаж всех товаров """ + +def sum_sales_for_each_product(lsts): + return [sum(lst["items_sold"]) for lst in lsts] + + +def avg_sales_for_each_product(lsts): + return [round(sum(lst["items_sold"])/len(lst["items_sold"])) for lst in lsts] + + +def sum_sales_for_all_products(lsts): + return sum(sum_sales_for_each_product(lsts)) + + +def avg_sales_for_all_products(lsts): + return round(sum_sales_for_all_products(lsts) / len(lsts)) + def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - + 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]}, + ] + for i in range(len(sales)): + print(f'Cуммарное количество продаж товара: "{sales[i]["product"]}" составляет {sum_sales_for_each_product(sales)[i]} шт.') + print('_' * 75) + + for i in range(len(sales)): + print(f'Среднее количество продаж товара: "{sales[i]["product"]}" составляет {avg_sales_for_each_product(sales)[i]} шт.') + print('_' * 75) + + print(f'Суммарное количество продаж товаров: "{", ".join([sale["product"] for sale in sales])}" составляет {sum_sales_for_all_products(sales)} шт.') + print('_' * 75) + + print(f'Среднее количество продаж товаров: "{", ".join([sale["product"] for sale in sales])}" составляет {avg_sales_for_all_products(sales)} шт.') + + if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..950c3507 100644 --- a/4_while1.py +++ b/4_while1.py @@ -4,18 +4,17 @@ Цикл while: hello_user -* Напишите функцию hello_user(), которая с помощью функции input() спрашивает +* Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” - + """ def hello_user(): - """ - Замените pass на ваш код - """ - pass + while True: + if input('Как дела?\n').capitalize() == 'Хорошо': + break + - if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..c5785c01 100644 --- a/5_while2.py +++ b/5_while2.py @@ -12,16 +12,21 @@ Пользователь: Что делаешь? Программа: Программирую - + """ -questions_and_answers = {} +questions_and_answers = {'как дела': 'Отлично!!!', 'кто ты': 'ИИ', + 'что делаешь': 'Программирую', + 'как тебя зовут': 'Секрет'} + def ask_user(answers_dict): - """ - Замените pass на ваш код - """ - pass - + while True: + question = input('Введите вопрос:\nUser: ').strip().lower() + if question.lower() in ['хватит', 'стоп', 'stop']: + break + print(answers_dict.get(question, 'Не знаю ответ на этот вопрос')) + + if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..be0d1be7 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -4,17 +4,20 @@ Исключения: KeyboardInterrupt -* Перепишите функцию hello_user() из задания while1, чтобы она - перехватывала KeyboardInterrupt, писала пользователю "Пока!" +* Перепишите функцию hello_user() из задания while1, чтобы она + перехватывала KeyboardInterrupt, писала пользователю "Пока!" и завершала работу при помощи оператора break - + """ def hello_user(): - """ - Замените pass на ваш код - """ - pass - + try: + while True: + if input('Как дела?\n').capitalize() == 'Хорошо': + break + except KeyboardInterrupt: + print('Пока!') + + if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..c826809f 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -10,15 +10,35 @@ * Первые два нужно приводить к вещественному числу при помощи float(), а третий - к целому при помощи int() и перехватывать исключения ValueError и TypeError, если приведение типов не сработало. - + """ -def discounted(price, discount, max_discount=20) - """ - Замените pass на ваш код - """ - pass - + +def discounted(price, discount, max_discount=20): + try: + price = abs(float(price)) + except (ValueError, TypeError) as _ex: + return f'Произошла ошибка {_ex}. Проверьте корректность введенной цены товара {price=}.' + + try: + discount = abs(float(discount)) + except (ValueError, TypeError) as _ex: + return f'Произошла ошибка {_ex}. Проверьте корректность введенной скидки на товар {discount=}.' + + try: + max_discount = abs(int(max_discount)) + except (ValueError, TypeError) as _ex: + return f'Произошла ошибка {_ex}. Проверьте корректность введенной максимальной ' \ + f'скидки на товар {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)) print(discounted(100, "3")) @@ -26,3 +46,5 @@ def discounted(price, discount, max_discount=20) print(discounted("five", 5)) print(discounted("сто", "десять")) print(discounted(100.0, 5, "10")) + print(discounted(None, 5, "10.0")) + print(discounted(100, 5, None)) diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..8621c3e0 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -13,42 +13,27 @@ """ import logging - from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +from settings import API_KEY +from handlers import greet_user, talk_to_me, constellation_planet, guess_number, choice_logo, user_coordinates 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' - } -} - - -def greet_user(update, context): - text = 'Вызван /start' - 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 main(): - mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True) + mybot = Updater(API_KEY, use_context=True) dp = mybot.dispatcher dp.add_handler(CommandHandler("start", greet_user)) + dp.add_handler(CommandHandler("planet", constellation_planet)) + dp.add_handler(CommandHandler("guess", guess_number)) + dp.add_handler(CommandHandler("logo", choice_logo)) + dp.add_handler(MessageHandler(Filters.regex('^(Отправить лого)$'), choice_logo)) + dp.add_handler(MessageHandler(Filters.location, user_coordinates)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) - + logging.info('Бот стартовал') mybot.start_polling() mybot.idle() diff --git a/handlers.py b/handlers.py new file mode 100644 index 00000000..84071de7 --- /dev/null +++ b/handlers.py @@ -0,0 +1,67 @@ +import ephem +from glob import glob +from datetime import date +from random import choice +from utils import get_smile, main_keyboard, play_random_game +from settings import IMG_PATH + + +def greet_user(update, context): + context.user_data['emoji'] = get_smile(context.user_data) + update.message.reply_text(f'Привет, {update["message"]["chat"]["first_name"]}! {context.user_data["emoji"]}', + reply_markup=main_keyboard()) + + +def talk_to_me(update, context): + user_text = update.message.text + print(user_text) + update.message.reply_text(user_text, + reply_markup=main_keyboard()) + + +def constellation_planet(update, context): + planets_name = { + '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() + con_planet = ephem.constellation(planets_name[planet](date.today())) + + if planet in planets_name: + update.message.reply_text( + f'Планета {planet.capitalize()} находится в созведии {con_planet[1]} ({con_planet[0]})', + reply_markup=main_keyboard() + ) + + +def guess_number(update, context): + if context.args: + try: + user_number = int(context.args[0]) + message = play_random_game(user_number) + except (TypeError, ValueError): + message = 'Введите целое число' + else: + message = 'Введите число' + update.message.reply_text(message, + reply_markup=main_keyboard()) + + +def choice_logo(update, context): + logos_path = glob(fr'{IMG_PATH}\logo*.jp*g') + logo_photos = choice(logos_path) + chat_id = update.effective_chat.id + context.bot.send_photo(chat_id, photo=open(logo_photos, 'rb'), + reply_markup=main_keyboard()) + + +def user_coordinates(update, context): + context.user_data['emoji'] = get_smile(context.user_data) + coords = update.message.location + update.message.reply_text(f'Ваши координаты: {coords} {context.user_data["emoji"]}', reply_markup=main_keyboard()) + print(f'{update.message.location} user: {update["message"]["chat"]["first_name"]}') diff --git a/images/logo1.jpg b/images/logo1.jpg new file mode 100644 index 00000000..af6c436b Binary files /dev/null and b/images/logo1.jpg differ diff --git a/images/logo2.jpg b/images/logo2.jpg new file mode 100644 index 00000000..a319198e Binary files /dev/null and b/images/logo2.jpg differ diff --git a/images/logo3.jpg b/images/logo3.jpg new file mode 100644 index 00000000..9f85a2e2 Binary files /dev/null and b/images/logo3.jpg differ diff --git a/images/logo4.jpg b/images/logo4.jpg new file mode 100644 index 00000000..b1ef8ad4 Binary files /dev/null and b/images/logo4.jpg differ diff --git a/utils.py b/utils.py new file mode 100644 index 00000000..c23bdb0e --- /dev/null +++ b/utils.py @@ -0,0 +1,27 @@ +from random import randint, choice +from settings import USER_EMOJI +from telegram import ReplyKeyboardMarkup, KeyboardButton +from emoji import emojize + + +def play_random_game(user_number): + bot_number = randint(user_number - 10, user_number + 10) + if user_number > bot_number: + message = f'Ваше число {user_number}, мое {bot_number}. Вы выиграли!' + elif user_number == bot_number: + message = f'Ваше число {user_number}, мое {bot_number}. У нас ничья' + else: + message = f'Ваше число {user_number}, мое {bot_number}. Вы проиграли(' + return message + + +def get_smile(user_data): + if 'emoji' not in user_data: + smile = choice(USER_EMOJI) + return emojize(smile, language='alias') + return user_data['emoji'] + + +def main_keyboard(): + return ReplyKeyboardMarkup([['Отправить лого', KeyboardButton('Мои координаты', request_location=True)], + ['Еще не придумал', 'Еще не придумал']])