-
Notifications
You must be signed in to change notification settings - Fork 453
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
finished work #130
base: master
Are you sure you want to change the base?
finished work #130
Changes from 2 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 | ||||
---|---|---|---|---|---|---|
|
@@ -16,12 +16,25 @@ | |||||
* Посчитать и вывести среднее количество продаж всех товаров | ||||||
""" | ||||||
|
||||||
def main(): | ||||||
""" | ||||||
Эта функция вызывается автоматически при запуске скрипта в консоли | ||||||
В ней надо заменить pass на ваш код | ||||||
""" | ||||||
pass | ||||||
|
||||||
def main(sales_figures): | ||||||
total_sales = average_sales = 0 | ||||||
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. Более привычный вариант
Suggested change
|
||||||
for i in sales_figures: | ||||||
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 происходит можно вынести отдельную функцию |
||||||
phone = i['product'] | ||||||
t_sale = a_sale = 0 | ||||||
for sale in i['items_sold']: | ||||||
t_sale += sale | ||||||
a_sale += 1 | ||||||
total_sales += sale | ||||||
average_sales += 1 | ||||||
print(f'суммарное количество продаж {phone}: {total_sales}, среднее количество продаж {phone}: {total_sales // average_sales}') | ||||||
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. Как правило большого пальца, давай будем разделять "посчитать", "подготовить сообщение" и вывести. |
||||||
print(f'суммарное количество продаж всех товаров: {total_sales}, среднее количество продаж всех товаров: {total_sales // average_sales}') | ||||||
|
||||||
sales_figures = [ | ||||||
{'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]}, | ||||||
] | ||||||
|
||||||
|
||||||
if __name__ == "__main__": | ||||||
main() | ||||||
main(sales_figures) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,11 +13,19 @@ | |
|
||
""" | ||
|
||
def discounted(price, discount, max_discount=20) | ||
""" | ||
Замените pass на ваш код | ||
""" | ||
pass | ||
def discounted(price, discount, max_discount=20): | ||
try: | ||
price = abs(float(price)) | ||
discount = abs(float(discount)) | ||
max_discount = abs(int(max_discount)) | ||
if max_discount >= 100: | ||
raise ValueError('Слишком большая максимальная скидка') | ||
if discount >= max_discount: | ||
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. я бы ожидал тут не строгое неравенство, что бы 20 процентов можно было использовать. |
||
return price | ||
else: | ||
return price - (price * discount / 100) | ||
except (ValueError, TypeError): | ||
return 'Некорректные аргументы' | ||
|
||
if __name__ == "__main__": | ||
print(discounted(100, 2)) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,57 +1,37 @@ | ||
""" | ||
Домашнее задание №1 | ||
|
||
Использование библиотек: ephem | ||
|
||
* Установите модуль ephem | ||
* Добавьте в бота команду /planet, которая будет принимать на вход | ||
название планеты на английском, например /planet Mars | ||
* В функции-обработчике команды из update.message.text получите | ||
название планеты (подсказка: используйте .split()) | ||
* При помощи условного оператора if и ephem.constellation научите | ||
бота отвечать, в каком созвездии сегодня находится планета. | ||
|
||
""" | ||
import logging | ||
|
||
import ephem | ||
from datetime import date | ||
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters | ||
|
||
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' | ||
} | ||
} | ||
import settings | ||
|
||
logging.basicConfig(filename='bot.log', level=logging.INFO) | ||
|
||
def greet_user(update, context): | ||
text = 'Вызван /start' | ||
print(text) | ||
update.message.reply_text(text) | ||
|
||
update.message.reply_text('Здравствуй пользователь!') | ||
|
||
def talk_to_me(update, context): | ||
user_text = update.message.text | ||
print(user_text) | ||
text = update.message.text | ||
update.message.reply_text(text) | ||
|
||
def planetary_constellation(update, context): | ||
current_date = date.today() | ||
planet_name = update.message.text.split()[-1].capitalize() | ||
planet = getattr(ephem, planet_name)(current_date) | ||
constellation = ephem.constellation(planet) | ||
update.message.reply_text(f'Планета {planet_name} находиться в созвездии: {constellation[-1]}') | ||
|
||
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', planetary_constellation)) | ||
dp.add_handler(MessageHandler(Filters.text, talk_to_me)) | ||
|
||
logging.info('bot started') | ||
mybot.start_polling() | ||
mybot.idle() | ||
|
||
|
||
if __name__ == "__main__": | ||
main() | ||
if __name__ == '__main__': | ||
main() |
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.
Если убрать блок else и делать после if return, у нас порядок исполнения кода не поменяется, а код станет чуть проще (менее вложенный, меньше блоков)