From d95546c2d97060df9a5c243cf8c9671858f9d5b4 Mon Sep 17 00:00:00 2001 From: aka-nomad Date: Mon, 16 Sep 2024 23:08:22 +0300 Subject: [PATCH 1/5] commit with homework --- 1_if1.py | 15 ++++++++++++++- 2_if2.py | 23 ++++++++++++++++++++++- 3_for.py | 19 ++++++++++++++++++- 4_while1.py | 8 ++++++-- 5_while2.py | 12 +++++++++++- 6_exception1.py | 12 +++++++++++- 7_exception2.py | 10 ++++++++-- 7 files changed, 90 insertions(+), 9 deletions(-) diff --git a/1_if1.py b/1_if1.py index be736084..c3bce084 100644 --- a/1_if1.py +++ b/1_if1.py @@ -19,7 +19,20 @@ def main(): Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + age = int(input('Please enter your age:')) + + def detect(age): + if 3 <= age <= 6: + return 'You should be in kindergarden' + elif 7 <= age <=18: + return 'You should be in school boy' + elif 18 <= age <= 23: + return 'You should be in University dude' + else: + return 'You should probably work man' + + result = detect (age) + print(result) if __name__ == "__main__": main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..30c3ba46 100644 --- a/2_if2.py +++ b/2_if2.py @@ -20,7 +20,28 @@ def main(): Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + def comapre_str(string1, string2): + if type(string1) is str and type(string2) is str: + len1 = len(string1) + len2 = len(string2) + + if len1 == len2: + return 1 + elif len1 > len2 and string2 != 'learn': + return 2 + elif string2 == 'learn': + return 3 + else: + return 'No rule for such combinations' + else: + return 0 + + for i in range(0, 4): + x = {0:1, 1:'Python',2:'hello', 3:'python3'} + y = {0:'Python', 1:'learn',2:'hello', 3:'PYTHON'} + result = comapre_str(x[i], y[i]) + print(result) + #print(x[i], y[i]) if __name__ == "__main__": main() diff --git a/3_for.py b/3_for.py index 5ca9f504..8bff6de8 100644 --- a/3_for.py +++ b/3_for.py @@ -21,7 +21,24 @@ def main(): Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + product_sell = [ + {'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_sale = 0 + + for i in range(len(product_sell)): + item = product_sell[i].get('product', 'no item') + sale = product_sell[i].get('items_sold', 0) + + sum_of_sale = sum(sale) + average_sale = sum(sale) // len(sale) + total_sale += sum_of_sale + + print(f"{item}, Total amount of sale: {sum_of_sale}, Average number of sale:{average_sale}") + + print(f"All items total sales: {total_sale}, All items average sales: {total_sale // len(product_sell)}") if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..1c06187f 100644 --- a/4_while1.py +++ b/4_while1.py @@ -14,8 +14,12 @@ def hello_user(): """ Замените pass на ваш код """ - pass - + answer = '' + + while True: + answer = input('How are you?') + if answer in ('Good', 'good'): + break if __name__ == "__main__": hello_user() diff --git a/5_while2.py b/5_while2.py index 49012dfd..e3d2ae05 100644 --- a/5_while2.py +++ b/5_while2.py @@ -21,7 +21,17 @@ def ask_user(answers_dict): """ Замените pass на ваш код """ - pass + dicts = { + "Как дела": "Хорошо!", "Что делаешь?": "Программирую", "Сколько тебе лет":"У меня нет возраста", "Любишь Питон":"Да" + } + while True: + answer = input("Задай свой вопрос:") + if answer in ("Пока", "пока"): + print("Пока!") + break + else: + print(f"Пользователь: {answer}{'\n'}Программа:{dicts.get(answer, 'У меня нет ответа на данный вопрос')}") + if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..358b3f45 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -14,7 +14,17 @@ def hello_user(): """ Замените pass на ваш код """ - pass + answer = '' + + while True: + try: + answer = input('How are you?') + if answer in ('Good', 'good'): + break + except KeyboardInterrupt: + print('\n', 'Good-bye!!!') + break + if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..17c0a9f9 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -13,11 +13,17 @@ """ -def discounted(price, discount, max_discount=20) +def discounted(price, discount, max_discount=20): """ Замените pass на ваш код """ - pass + try: + price, discount, max_discount = float(price), float(discount), int(max_discount) + if max_discount >= 100: + raise ValueError('Слишком большая максимальная скидка') + return price - (price * discount / 100) + except (ValueError, TypeError): + print('Переданы некорректные аргументы или не сработало приведение типов данных!') if __name__ == "__main__": print(discounted(100, 2)) From ab1e1feccdbaaeca7e9c0f9130187d82fd76adf3 Mon Sep 17 00:00:00 2001 From: Dilshat Mukhambetaliev Date: Mon, 23 Sep 2024 11:49:21 +0300 Subject: [PATCH 2/5] telegram bot added --- 8_ephem_bot.py | 29 +++++++++++++++++++++++++---- settings.py | 1 + 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 settings.py diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..f1b0f4f7 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -12,7 +12,7 @@ бота отвечать, в каком созвездии сегодня находится планета. """ -import logging +import logging, ephem, settings, datetime from telegram.ext import Updater, CommandHandler, MessageHandler, Filters @@ -20,7 +20,7 @@ level=logging.INFO, filename='bot.log') - +""" PROXY = { 'proxy_url': 'socks5://t1.learn.python.ru:1080', 'urllib3_proxy_kwargs': { @@ -28,7 +28,27 @@ 'password': 'python' } } +""" +def get_constellation(update, context): + try: + user_planet = update.message.text.split()[1].lower() + current_date = datetime.datetime.now().strftime('%Y/%m/%d') + planets = { + 'mercury': ephem.Mercury(), 'venus':ephem.Venus(), 'mars':ephem.Mars(),'jupiter':ephem.Jupiter(), + 'saturn':ephem.Saturn(), 'uranus':ephem.Uranus(), 'neptun':ephem.Neptune() + } + + if user_planet != '': + planet = planets.get(user_planet) + compute = planet.compute(current_date) + update.message.reply_text(ephem.constellation(planet)[1]) + except IndexError: + update.message.reply_text('ERROR! You do not determine the planet') + + u = ephem.planet + print() + ephem.constellation def greet_user(update, context): text = 'Вызван /start' @@ -39,14 +59,15 @@ 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 main(): - mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True) + mybot = Updater(settings.API_KEY) 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() diff --git a/settings.py b/settings.py new file mode 100644 index 00000000..53861cb2 --- /dev/null +++ b/settings.py @@ -0,0 +1 @@ +API_KEY = "7475700629:AAHvNdrcCzOdt2odHBippgfS7rFns1wAGQc" \ No newline at end of file From 1d4dfae9fa9f136fbfa61b8e2fa77f0a444f8315 Mon Sep 17 00:00:00 2001 From: Dilshat Mukhambetaliev Date: Mon, 23 Sep 2024 12:11:36 +0300 Subject: [PATCH 3/5] edit task 2 after comments --- 2_if2.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/2_if2.py b/2_if2.py index 30c3ba46..cadb1753 100644 --- a/2_if2.py +++ b/2_if2.py @@ -27,9 +27,9 @@ def comapre_str(string1, string2): if len1 == len2: return 1 - elif len1 > len2 and string2 != 'learn': + elif len1 > len2: return 2 - elif string2 == 'learn': + elif string2 == 'learn' and string2 != 'learn': return 3 else: return 'No rule for such combinations' @@ -37,7 +37,7 @@ def comapre_str(string1, string2): return 0 for i in range(0, 4): - x = {0:1, 1:'Python',2:'hello', 3:'python3'} + x = {0:1, 1:'Learn',2:'hello', 3:'python3'} y = {0:'Python', 1:'learn',2:'hello', 3:'PYTHON'} result = comapre_str(x[i], y[i]) print(result) From 075dde2d2b7d2a9af0c2e02c0069543a0c2e2318 Mon Sep 17 00:00:00 2001 From: Dilshat Mukhambetaliev Date: Mon, 23 Sep 2024 12:40:22 +0300 Subject: [PATCH 4/5] tasks edited after review --- 2_if2.py | 2 +- 3_for.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/2_if2.py b/2_if2.py index cadb1753..6c3b0412 100644 --- a/2_if2.py +++ b/2_if2.py @@ -29,7 +29,7 @@ def comapre_str(string1, string2): return 1 elif len1 > len2: return 2 - elif string2 == 'learn' and string2 != 'learn': + elif string1 != string2: return 3 else: return 'No rule for such combinations' diff --git a/3_for.py b/3_for.py index 8bff6de8..629fbf3a 100644 --- a/3_for.py +++ b/3_for.py @@ -27,18 +27,20 @@ def main(): {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, ] total_sale = 0 + total_average_sale = 0 for i in range(len(product_sell)): item = product_sell[i].get('product', 'no item') sale = product_sell[i].get('items_sold', 0) sum_of_sale = sum(sale) - average_sale = sum(sale) // len(sale) + average_sale = sum(sale) / len(sale) total_sale += sum_of_sale + total_average_sale += average_sale print(f"{item}, Total amount of sale: {sum_of_sale}, Average number of sale:{average_sale}") - print(f"All items total sales: {total_sale}, All items average sales: {total_sale // len(product_sell)}") + print(f"All items total sales: {total_sale}, All items average sales: {total_average_sale}") if __name__ == "__main__": main() From c3e536da28b83a07fe2110f9739546ca779ff4ba Mon Sep 17 00:00:00 2001 From: Dilshat Mukhambetaliev Date: Mon, 23 Sep 2024 13:22:49 +0300 Subject: [PATCH 5/5] edited tasks after review --- 4_while1.py | 4 ++-- 5_while2.py | 9 ++++++--- 7_exception2.py | 10 ++++++---- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/4_while1.py b/4_while1.py index 1c06187f..925456aa 100644 --- a/4_while1.py +++ b/4_while1.py @@ -17,8 +17,8 @@ def hello_user(): answer = '' while True: - answer = input('How are you?') - if answer in ('Good', 'good'): + answer = input('How are you?').lower() + if answer == "good": break if __name__ == "__main__": diff --git a/5_while2.py b/5_while2.py index e3d2ae05..0e814461 100644 --- a/5_while2.py +++ b/5_while2.py @@ -22,16 +22,19 @@ def ask_user(answers_dict): Замените pass на ваш код """ dicts = { - "Как дела": "Хорошо!", "Что делаешь?": "Программирую", "Сколько тебе лет":"У меня нет возраста", "Любишь Питон":"Да" + "как дела": "Хорошо!", "что делаешь": "Программирую", "сколько тебе лет":"У меня нет возраста", "любишь питон":"Да" } while True: - answer = input("Задай свой вопрос:") + answer = input("Задай свой вопрос:").lower() + if answer[-1] == '?': + answer = answer.rstrip('?') + if answer in ("Пока", "пока"): print("Пока!") break else: - print(f"Пользователь: {answer}{'\n'}Программа:{dicts.get(answer, 'У меня нет ответа на данный вопрос')}") + print(f"Пользователь: {answer}\nПрограмма:{dicts.get(answer, 'У меня нет ответа на данный вопрос')}") if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/7_exception2.py b/7_exception2.py index 17c0a9f9..996d3ae5 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -22,13 +22,15 @@ def discounted(price, discount, max_discount=20): if max_discount >= 100: raise ValueError('Слишком большая максимальная скидка') return price - (price * discount / 100) - except (ValueError, TypeError): - print('Переданы некорректные аргументы или не сработало приведение типов данных!') + except ValueError: + print('Переданы некорректные аргументы') + except TypeError: + print('Не сработало приведение типов данных!') 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("сто", "десять","five")) + print(discounted(100.0, 100, "10"))