diff --git a/1_if1.py b/1_if1.py index be736084..47453490 100644 --- a/1_if1.py +++ b/1_if1.py @@ -1,25 +1,14 @@ -""" +age = int(input("Введите ваш возраст: ")) +def what_to_do(age): + if age < 7: + return "Вы будете ходить в детский сад." + elif age < 18: + return "Вы будете учиться в школе." + elif age < 24: + return "Вы будете работать." + else: + return "Вам нужно работать." +result = what_to_do(age) +print(result) -Домашнее задание №1 -Условный оператор: Возраст - -* Попросить пользователя ввести возраст при помощи input и положить - результат в переменную -* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: - учиться в детском саду, школе, ВУЗе или работать -* Вызвать функцию, передав ей возраст пользователя и положить результат - работы функции в переменную -* Вывести содержимое переменной на экран - -""" - -def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - -if __name__ == "__main__": - main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..e1394c57 100644 --- a/2_if2.py +++ b/2_if2.py @@ -1,26 +1,20 @@ -""" - -Домашнее задание №1 - -Условный оператор: Сравнение строк - -* Написать функцию, которая принимает на вход две строки -* Проверить, является ли то, что передано функции, строками. - Если нет - вернуть 0 -* Если строки одинаковые, вернуть 1 -* Если строки разные и первая длиннее, вернуть 2 -* Если строки разные и вторая строка 'learn', возвращает 3 -* Вызвать функцию несколько раз, передавая ей разные праметры - и выводя на экран результаты - -""" - +def compare_strings(str1, str2): + if type(str1) != str or type(str2) != str: + return 0 + elif str1 == str2: + return 1 + elif str2 == "learn": + return 3 + elif len(str1) > len(str2): + return 2 + else: + return None def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass - + + print (compare_strings("hello", "hello")) + print(compare_strings("python", "learn")) + print(compare_strings("hello", "hi")) +print(compare_strings(10, "hello")) +print(compare_strings("hi", "hello")) if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/3_for.py b/3_for.py index 5ca9f504..56a86be2 100644 --- a/3_for.py +++ b/3_for.py @@ -16,12 +16,34 @@ * Посчитать и вывести среднее количество продаж всех товаров """ -def main(): - """ + + +""" Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass - +def main(): + + sales_data = [ + {'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]}, + ] + + total_all = 0 + count_all = 0 + + for product in sales_data: + total = sum(product['items_sold']) + average = total / len(product['items_sold']) + print(product['product'], ": суммарные", total, ", средние", average) + total_all += total + count_all += len(product['items_sold']) + + print("Суммарные продажи всех товаров:", total_all) + print("Средние продажи всех товаров:", total_all / count_all) + + + if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..0fa9de37 100644 --- a/4_while1.py +++ b/4_while1.py @@ -14,7 +14,13 @@ def hello_user(): """ Замените pass на ваш код """ - pass +answer = "" +while answer != "Хорошо": + answer = input ("Как дела? ") + print("Я рад,что всё хорошо") + + + if __name__ == "__main__": diff --git a/5_while2.py b/5_while2.py index 49012dfd..d778e65a 100644 --- a/5_while2.py +++ b/5_while2.py @@ -15,13 +15,24 @@ """ -questions_and_answers = {} +questions_and_answers = {"Как дела?": "Хорошо!", +"Что делаешь?": "Программирую", +"Как тебяя зовут?": "Я бот-помощник" +} def ask_user(answers_dict): """ Замените pass на ваш код """ - pass - + + while True: + user_question = input("Задайте вопрос: ") + + if user_question in answers_dict: + print(answers_dict[user_question]) + else: + print("Я не знаю ответа на этот вопрос.") + + if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..73d52fe2 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -14,7 +14,15 @@ def hello_user(): """ Замените pass на ваш код """ - pass +answer = "" +while answer != "Хорошо": + try: + answer = input("Как дела? ") + if answer == "Хорошо": + print("Я рад, что всё хорошо") + except KeyboardInterrupt: + print("\nПока!") + break if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..75acae85 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -13,12 +13,25 @@ """ -def discounted(price, discount, max_discount=20) +def discounted(price, discount, max_discount=20): + """ Замените pass на ваш код """ - pass - + try: + price = float(price) + discount = float(discount) + max_discount = int(max_discount) + except (ValueError, TypeError): + print("Ошибка: неверные данные") + return + + if discount > max_discount: + discount = max_discount + + return price - (price * discount / 100) + + 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..195402c3 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -13,6 +13,8 @@ """ import logging +import ephem +import datetime from telegram.ext import Updater, CommandHandler, MessageHandler, Filters @@ -39,7 +41,30 @@ 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) + + +def planet(update, context): + user_text = update.message.text + parts = user_text.split() + + if len(parts) < 2: + update.message.reply_text("Напишите: /planet Mars") + return + + planet_name = parts[1] + + try: + planet_class = getattr(ephem, planet_name) + planet_obj = planet_class(datetime.date.today()) + + constellation = ephem.constellation(planet_obj) + update.message.reply_text( + f"Планета {planet_name} сейчас в созвездии {constellation[1]}" + ) + + except AttributeError: + update.message.reply_text("Я не знаю такую планету") def main(): @@ -47,6 +72,7 @@ def main(): dp = mybot.dispatcher dp.add_handler(CommandHandler("start", greet_user)) + dp.add_handler(CommandHandler("planet", planet)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) mybot.start_polling() diff --git a/test b/test new file mode 100644 index 00000000..4ab2c3c0 --- /dev/null +++ b/test @@ -0,0 +1,22 @@ +def discounted(price, discount, max_discount=20): + try: + price = float(price) + discount = float(discount) + max_discount = int(max_discount) + except (ValueError, TypeError): + print("Ошибка: некорректные данные") + return + + if discount > max_discount: + discount = max_discount + + 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")) \ No newline at end of file