-
Notifications
You must be signed in to change notification settings - Fork 474
Alexandra Poturaeva #137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Alexandra Poturaeva #137
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -121,3 +121,7 @@ dmypy.json | |
|
|
||
| # Pyre type checker | ||
| .pyre/ | ||
|
|
||
| .idea/ | ||
| settings.py | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,22 +4,48 @@ | |
|
|
||
| Условный оператор: Возраст | ||
|
|
||
| * Попросить пользователя ввести возраст при помощи input и положить | ||
| * Попросить пользователя ввести возраст при помощи input и положить | ||
| результат в переменную | ||
| * Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: | ||
| * Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: | ||
| учиться в детском саду, школе, ВУЗе или работать | ||
| * Вызвать функцию, передав ей возраст пользователя и положить результат | ||
| * Вызвать функцию, передав ей возраст пользователя и положить результат | ||
| работы функции в переменную | ||
| * Вывести содержимое переменной на экран | ||
|
|
||
| """ | ||
|
|
||
| from typing import Optional | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💯👌 |
||
|
|
||
|
|
||
| def define_occupation_by_age(age: int) -> Optional[str]: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно придумать разумное "дефолтное значение" и сделать функцию -> str. |
||
| """ | ||
| Function get user age and define their expected occupation | ||
| """ | ||
| if 0 <= age < 7: | ||
| return 'учиться в детском саду' | ||
| elif 7 <= age < 17: | ||
| return 'учиться в школе' | ||
| elif 17 <= age < 24: | ||
| return 'учиться в ВУЗе' | ||
| elif 24 <= age < 65: | ||
| return 'работать' | ||
| elif 65 <= age <= 120: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. C точки зрения типизации, функция все еще возвращает Optional, потому что при возрасте больше 120 вернет None |
||
| return 'отдыхать (быть пенсионером)' | ||
|
|
||
|
|
||
| def main(): | ||
| """ | ||
| Эта функция вызывается автоматически при запуске скрипта в консоли | ||
| В ней надо заменить pass на ваш код | ||
| """ | ||
| pass | ||
| while True: | ||
| user_age = int(input('Введите возраст (от 0 до 120 лет): ')) | ||
| if user_age < 0 or user_age > 120: | ||
| print('Возраст введён некорректно, попробуйте ещё раз') | ||
| else: | ||
| user_expected_occupation = define_occupation_by_age(user_age) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. здесь все равно ты не обрабатывешь None |
||
| print(f'Ожидается, что в этом возрасте человек должен {user_expected_occupation}') | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,22 +5,35 @@ | |
| Условный оператор: Сравнение строк | ||
|
|
||
| * Написать функцию, которая принимает на вход две строки | ||
| * Проверить, является ли то, что передано функции, строками. | ||
| * Проверить, является ли то, что передано функции, строками. | ||
| Если нет - вернуть 0 | ||
| * Если строки одинаковые, вернуть 1 | ||
| * Если строки разные и первая длиннее, вернуть 2 | ||
| * Если строки разные и вторая строка 'learn', возвращает 3 | ||
| * Вызвать функцию несколько раз, передавая ей разные праметры | ||
| * Вызвать функцию несколько раз, передавая ей разные праметры | ||
| и выводя на экран результаты | ||
|
|
||
| """ | ||
|
|
||
|
|
||
| def compare_strings(string_1: str, string_2: str) -> int: | ||
| if not all([isinstance(string_1, str), isinstance(string_2, str)]): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тк их всего 2, лучше заменить all обычный or |
||
| return 0 | ||
| elif string_1 == string_2: | ||
| return 1 | ||
| elif len(string_1) > len(string_2) and string_2 != 'learn': | ||
| return 2 | ||
| elif string_1 != string_2 and string_2 == 'learn': | ||
| return 3 | ||
|
|
||
|
|
||
| def main(): | ||
| """ | ||
| Эта функция вызывается автоматически при запуске скрипта в консоли | ||
| В ней надо заменить pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| print(compare_strings(1, 'string')) | ||
| print(compare_strings('string', 'string')) | ||
| print(compare_strings('strings', 'string')) | ||
| print(compare_strings('string', 'learn')) | ||
| print(compare_strings('learn', 'string')) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,36 @@ | |
| * Посчитать и вывести среднее количество продаж всех товаров | ||
| """ | ||
|
|
||
| sales_info = [ | ||
| {'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 main(): | ||
| """ | ||
| Эта функция вызывается автоматически при запуске скрипта в консоли | ||
| В ней надо заменить pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| total_sales = 0 | ||
| total_sale_times = 0 | ||
|
|
||
| print('1-2. Суммарное/среднее количество продаж по товарам:') | ||
| for product in sales_info: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. разбей решение на несколько функций |
||
| total_product_sales = sum(product["items_sold"]) | ||
| total_product_sale_times = len(product["items_sold"]) | ||
| avg_product_sales = round(total_product_sales/total_product_sale_times) | ||
|
|
||
| total_sales += total_product_sales | ||
| total_sale_times += total_product_sale_times | ||
|
|
||
| print(f'\t{product["product"]} - {total_product_sales}/{avg_product_sales}') | ||
|
|
||
| print(f'\n3. Cуммарное количество продаж всех товаров: {total_sales}') | ||
|
|
||
| print(f'\n4. Cреднее количество продаж всех товаров: {round(total_sales/total_sale_times)}') | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,15 +10,34 @@ | |
| * Первые два нужно приводить к вещественному числу при помощи float(), | ||
| а третий - к целому при помощи int() и перехватывать исключения | ||
| ValueError и TypeError, если приведение типов не сработало. | ||
|
|
||
| """ | ||
| import traceback | ||
|
|
||
|
|
||
| def discounted(price, discount, max_discount=20): | ||
| try: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В try должно быть как можно меньше кода, здесь ты пытаешься перехватить всех , и потом в обработке исключения пытаешься понять что же все таки происходило. |
||
| price = float(price) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Все еще не обернуты по одному |
||
| discount = float(discount) | ||
| max_discount = int(max_discount) | ||
| if max_discount >= 100: | ||
| raise Exception('Слишком большая максимальная скидка') | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Exception - слишком широкий класс, используй что-то вроде ValueError |
||
| if discount >= max_discount: | ||
| return price | ||
| else: | ||
| return price - (price * discount / 100) | ||
| except ValueError: | ||
| traceback_split = traceback.format_exc().split() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🫨 |
||
| for var in discounted.__code__.co_varnames[:2]: | ||
| if var in traceback_split: | ||
| return f'Неверное значение переменной {var}' | ||
| except TypeError: | ||
| traceback_split = traceback.format_exc().split() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Очень интересная, но и неожиданная идея, обрабатывать так исключения. Этого не должно быть в бизнес коде (а эта функция это бизнес код). |
||
| for var in discounted.__code__.co_varnames[:2]: | ||
| if var in traceback_split: | ||
| return f'Неверный тип переменной {var}' | ||
|
|
||
|
|
||
| def discounted(price, discount, max_discount=20) | ||
| """ | ||
| Замените pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| if __name__ == "__main__": | ||
| print(discounted(100, 2)) | ||
| print(discounted(100, "3")) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,42 +13,62 @@ | |
|
|
||
| """ | ||
| import logging | ||
| import time | ||
| from datetime import date | ||
| import settings | ||
| import ephem | ||
|
|
||
| from telegram.ext import Updater, CommandHandler, MessageHandler, Filters | ||
|
|
||
| logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', | ||
| level=logging.INFO, | ||
| filename='bot.log') | ||
| logging.Formatter.converter = time.gmtime | ||
| logging.basicConfig( | ||
| filename='bot.log', | ||
| level=logging.INFO, | ||
| datefmt='%d.%m.%Y %H:%M:%S', | ||
| format='%(asctime)s (GMT+0) %(message)s', | ||
| encoding='utf-8' | ||
| ) | ||
|
|
||
|
|
||
| PROXY = { | ||
| 'proxy_url': 'socks5://t1.learn.python.ru:1080', | ||
| 'urllib3_proxy_kwargs': { | ||
| 'username': 'learn', | ||
| 'password': 'python' | ||
| } | ||
| } | ||
| def greet_user(update, context): | ||
| print('Вызван /start') | ||
| update.message.reply_text('Здравствуй, пользователь!') | ||
|
|
||
|
|
||
| def greet_user(update, context): | ||
| text = 'Вызван /start' | ||
| def talk_to_me(update, context): | ||
| text = update.message.text | ||
| 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 check_current_planet_constellation(update, context): | ||
| current_date = date.today() | ||
| ephem_planets = { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
| '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() | ||
|
|
||
| if planet in ephem_planets: | ||
| update.message.reply_text( | ||
| f'Today {planet.capitalize()} is in {ephem.constellation(ephem_planets[planet](current_date))}' | ||
| ) | ||
|
|
||
|
|
||
| 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('start', greet_user)) | ||
| dp.add_handler(CommandHandler('planet', check_current_planet_constellation)) | ||
| dp.add_handler(MessageHandler(Filters.text, talk_to_me)) | ||
|
|
||
| logging.info('Бот стартовал') | ||
| mybot.start_polling() | ||
| mybot.idle() | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше вносить это в .gitignore и не коммитить