Skip to content
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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,17 @@

"""

def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
def main(age):
if age < 7:
return "Вы должны быть в детском саду"
elif 7 <= age < 18:
return "Вы должны учиться в школе"
elif 18 <= age < 22:
return "Вы должны учиться в ВУЗе"
else:
return "Вы должны работать"

age = int(input("Введите возраст: "))

if __name__ == "__main__":
main()
main(age)
28 changes: 25 additions & 3 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,34 @@

"""

def main():
def main(str_1, str_2):
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
if isinstance(str_1, str) and isinstance(str_2, str):
if str_1 == str_2:
return 1
elif str_2 == "learn":
return 3
elif len(str_1) > len(str_2):
return 2
return 0

str_1, str_2 = '123', 2
print(main(str_1, str_2))

str_1, str_2 = '123', '123'
print(main(str_1, str_2))

str_1, str_2 = '123', '2'
print(main(str_1, str_2))

str_1, str_2 = '123', 'learn'
print(main(str_1, str_2))

str_1, str_2 = '123', '1234'
print(main(str_1, str_2))

if __name__ == "__main__":
main()
main(str_1, str_2)
42 changes: 34 additions & 8 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,39 @@
* Посчитать и вывести суммарное количество продаж всех товаров
* Посчитать и вывести среднее количество продаж всех товаров
"""
def phone_sales_amount(items_sold):
total_sales, number_of_sales = 0, 0
for sale in items_sold:
total_sales += sale
number_of_sales += 1
average_sales = total_sales // number_of_sales
return total_sales, average_sales
def total_number_of_sales_for_each_product(phone, total_sales):
return f'Всего продаж {phone}: {total_sales}'
def average_number_of_sales_for_each_product(phone, average_sales):
return f'Средние количетсво продаж {phone}: {average_sales}'
def total_and_average_number_of_phone_sales(sales_figures):
total_sales, number_of_sales = 0, 0
for dict in sales_figures:
total_sales += phone_sales_amount(dict['items_sold'])[0]
number_of_sales += 1
average_number_of_phone_sales = total_sales // number_of_sales
return total_sales, average_number_of_phone_sales


def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

if __name__ == "__main__":
main()
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]},
]
for dict in sales_figures:
phone = dict['product']
total_sales = phone_sales_amount(dict['items_sold'])[0]
print(total_number_of_sales_for_each_product(phone, total_sales))
for dict in sales_figures:
phone = dict['product']
average_sales = phone_sales_amount(dict['items_sold'])[1]
print(average_number_of_sales_for_each_product(phone, average_sales))
print(f'Сумммарное количество продаж всех товаров: {total_and_average_number_of_phone_sales(sales_figures)[0]}')
print(f'Средние количество продаж всех товаров: {total_and_average_number_of_phone_sales(sales_figures)[1]}')
11 changes: 5 additions & 6 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@


def hello_user():
"""
Замените pass на ваш код
"""
pass


while True:
user_say = input('Как дела? ')
if user_say == 'Хорошо':
break

if __name__ == "__main__":
hello_user()
13 changes: 8 additions & 5 deletions 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@

"""

questions_and_answers = {}
questions_and_answers = {"Как дела?": "Хорошо!",
"Что делаешь?": "Программирую"

}

def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
while True:
user_say = input("Введите вопрос: ")
if user_say in questions_and_answers:
print(f'Программа: {questions_and_answers[user_say]}')

if __name__ == "__main__":
ask_user(questions_and_answers)
11 changes: 7 additions & 4 deletions 6_exception1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
"""

def hello_user():
"""
Замените pass на ваш код
"""
pass
try:
while True:
user_say = input('Как дела?\n')
if user_say == 'Хорошо':
break
except KeyboardInterrupt:
print('Пока!')

if __name__ == "__main__":
hello_user()
18 changes: 13 additions & 5 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
return price
else:
return price - (price * discount / 100)
except (ValueError, TypeError):
return 'Некорректные аргументы'

if __name__ == "__main__":
print(discounted(100, 2))
Expand Down
56 changes: 18 additions & 38 deletions 8_ephem_bot.py
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()