diff --git a/.gitignore b/.gitignore index af6d5026..ba5c3f6c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +settings.py # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/1_if1.py b/1_if1.py index be736084..a56e6b20 100644 --- a/1_if1.py +++ b/1_if1.py @@ -13,13 +13,33 @@ * Вывести содержимое переменной на экран """ +def prof_by_age(age): + if age <= 6: + return 'учиться в детском саду' + elif age < 18: + return 'учится в школе' + else: + return 'учиться в ВУЗе или работать' def main(): - """ - Эта функция вызывается автоматически при запуске скрипта в консоли - В ней надо заменить pass на ваш код - """ - pass + while True: + try: + age = int(input('----Для выхода введите 0 ----\nВведите ваш возраст: ')) + if age == 0: + break + else: + prof = prof_by_age(age) + print(f"По возрасту вам положено {prof}") + except ValueError: + print('Введите ваш возраст цифрами!') + continue + + + """ + Эта функция вызывается автоматически при запуске скрипта в консоли + В ней надо заменить pass на ваш код + """ + #pass if __name__ == "__main__": main() diff --git a/2_if2.py b/2_if2.py index 0f1644f3..22264bb7 100644 --- a/2_if2.py +++ b/2_if2.py @@ -14,13 +14,34 @@ и выводя на экран результаты """ +def two_strings(one, two): + a = isinstance(one, str) + b = isinstance(two, str) + if a and b: + if one == two: + return 1 + elif two == 'learn': + return 3 + elif len(one) > len(two): + return 2 + else: + pass + else: + return 0 + def main(): + print(two_strings('hfp','hfp')) + print(two_strings('hfpsdf','hfp')) + print(two_strings('lkj',1)) + print(two_strings(4,4)) + print(two_strings('sdfsfds','learn')) + """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + #pass if __name__ == "__main__": main() diff --git a/3_for.py b/3_for.py index 5ca9f504..f17ac94c 100644 --- a/3_for.py +++ b/3_for.py @@ -5,23 +5,54 @@ Цикл for: Продажи товаров * Дан список словарей с данными по колличеству проданных телефонов - [ +""" +lst_phone = [ {'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 sum_list_prod(lst): + for product in lst: + print('Cуммарное количество продаж ',product['product'],'- ',sum(product['items_sold'])) + +def average_lst(lst): + for product in lst: + avrge_lst = round((sum(product['items_sold'])/len(product['items_sold'])),2) + print('Cреднее количество продаж ', product['product'],'- ',avrge_lst) + +def sum_sold(lst): + s = 0 + for product in lst: + a = sum(product['items_sold']) + s += a + print('Cуммарное количество продаж всех товаров ', s) + +def avrge_sold(lst): + count = 0 + a = 0 + for i in lst: + avrge = round((sum(i['items_sold'])/len(i['items_sold'])),2) + a += avrge + count += 1 + print('Cреднее количество продаж всех товаров ', a/count) def main(): + sum_list_prod(lst_phone) + average_lst(lst_phone) + sum_sold(lst_phone) + avrge_sold(lst_phone) + """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ - pass + #pass if __name__ == "__main__": main() diff --git a/4_while1.py b/4_while1.py index b5791517..d024ca79 100644 --- a/4_while1.py +++ b/4_while1.py @@ -11,10 +11,17 @@ def hello_user(): - """ - Замените pass на ваш код - """ - pass + while True: + try: + whatsup = input('Как дела?:') + if whatsup.lower() == 'хорошо': + break + else: + continue + except KeyboardInterrupt: + break + + if __name__ == "__main__": diff --git a/5_while2.py b/5_while2.py index 49012dfd..76b0af01 100644 --- a/5_while2.py +++ b/5_while2.py @@ -1,3 +1,4 @@ +import urllib.request """ Домашнее задание №1 @@ -14,14 +15,27 @@ Программа: Программирую """ - -questions_and_answers = {} +def external_ip(): + external_ip = str(urllib.request.urlopen('https://ident.me').read().decode('utf8')) #Обработать try/except + return external_ip +ext_ip = external_ip() +questions_and_answers = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую", "Какой у тебя ip?": f'{ext_ip}'} +quest = ''.join(f'{k}'+',' for k in questions_and_answers.keys()) def ask_user(answers_dict): - """ - Замените pass на ваш код - """ - pass + q = f'Возможные вопросы:\n{quest}' + print(q) + while True: + try: + questions = (input('Введите вопрос:')).lower() + a = questions_and_answers.get(questions.capitalize()) + if a: + print(a) + else: + print(f'----Введите вопрос из списка!----\n{q}\nЧтобы выйти, нажмите Ctrl+C') + continue + except KeyboardInterrupt: + break if __name__ == "__main__": ask_user(questions_and_answers) diff --git a/6_exception1.py b/6_exception1.py index 3ea9d054..cd78b3cd 100644 --- a/6_exception1.py +++ b/6_exception1.py @@ -11,10 +11,17 @@ """ def hello_user(): - """ - Замените pass на ваш код - """ - pass + while True: + try: + whatsup = input('Как дела?:') + if whatsup.lower() == 'хорошо': + break + else: + continue + except KeyboardInterrupt: + print('\nПока!') + break + if __name__ == "__main__": hello_user() diff --git a/7_exception2.py b/7_exception2.py index d4bd8a39..05cfe739 100644 --- a/7_exception2.py +++ b/7_exception2.py @@ -13,12 +13,19 @@ """ -def discounted(price, discount, max_discount=20) - """ - Замените pass на ваш код - """ - pass - +def discounted(price, discount, max_discount=20): + try: + price_float = float(price) + discount_float = float(discount) + max_discount_int = int(max_discount) + return (price_float, discount_float, max_discount_int) + except TypeError: + return ('TypeError') + except ValueError: + return ('ValueError') + + + if __name__ == "__main__": print(discounted(100, 2)) print(discounted(100, "3")) @@ -26,3 +33,5 @@ def discounted(price, discount, max_discount=20) print(discounted("five", 5)) print(discounted("сто", "десять")) print(discounted(100.0, 5, "10")) + print(discounted([100.0,], 5, "10")) + diff --git a/8_ephem_bot.py b/8_ephem_bot.py index 1cf9ea19..a100e8de 100644 --- a/8_ephem_bot.py +++ b/8_ephem_bot.py @@ -13,22 +13,23 @@ """ import logging - +import ephem from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +import settings +from datetime import date logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO, filename='bot.log') -PROXY = { +""" PROXY = { 'proxy_url': 'socks5://t1.learn.python.ru:1080', 'urllib3_proxy_kwargs': { 'username': 'learn', 'password': 'python' } -} - +} """ def greet_user(update, context): text = 'Вызван /start' @@ -39,15 +40,40 @@ 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): + dt_now = date.today() + b = update.message.text #(update['message'])['text'] + d = ((b.split())[1]).lower() + if d == 'mars': + m = ephem.Mars(dt_now.year) + elif d == 'mercury': + m = ephem.Mercury(dt_now.year) + elif d == 'venus': + m = ephem.Venus(dt_now.year) + elif d == 'jupiter': + m = ephem.Jupiter(dt_now.year) + elif d == 'saturn': + m = ephem.Saturn(dt_now.year) + elif d == 'uranus': + m = ephem.Uranus(dt_now.year) + elif d == 'neptune': + m = ephem.Neptune(dt_now.year) + elif d == 'pluto': + m = ephem.Pluto(dt_now.year) + else: + update.message.reply_text('Не знаю такую планету') + update.message.reply_text(ephem.constellation(m)) 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", planet)) dp.add_handler(MessageHandler(Filters.text, talk_to_me)) + mybot.start_polling() mybot.idle()