Skip to content
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,5 @@ dmypy.json

# Pyre type checker
.pyre/

Setting.py
23 changes: 18 additions & 5 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,25 @@

"""


def years_print(years_old):
stroka = ""
if years_old < 7:
stroka = "Человек учится в детском саду."
elif 7 <= years_old < 17:
stroka = "Человек учится в школе."
elif 17 <= years_old < 22:
stroka = "Человек учится в ВУЗе."
else:
stroka = "Человек работает."
return stroka


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

years_old = input("Введите ваш возраст: ")
print(years_print(int(years_old)))


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

"""


def comparison_str(string1, string2):

if type(string1) != str or type(string2) != str:
return 0
elif string1 == string2:
return 1
elif len(string1) > len(string2):
return 2
elif string2 == "learn":
return 3
else:
return 4


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


string1 = input("Введите первую строку: ")
string2 = input("Введите вторую строку: ")
print(comparison_str(string1, string2))
print(comparison_str(12, string2))


if __name__ == "__main__":
main()
36 changes: 30 additions & 6 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,36 @@
* Посчитать и вывести среднее количество продаж всех товаров
"""


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

list_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],
},
]
all_sum = 0
all_len = 0
for amount_phone in list_phone:
print(sum(amount_phone["items_sold"]))
all_sum += sum(amount_phone["items_sold"])
if len(amount_phone["items_sold"]) > 0:
middle_num = sum(amount_phone["items_sold"]) / len(
amount_phone["items_sold"]
)
print(middle_num)
all_len += len(amount_phone["items_sold"])
print(all_sum)
print(all_sum / all_len)


if __name__ == "__main__":
main()
9 changes: 4 additions & 5 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 input("Как дела? ") != "Хорошо":
pass


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

"""

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


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


while True:
question_in = input("Задайте вопрос: ").strip()
if answers_dict.get(question_in):
print(answers_dict.get(question_in))
break
else:
print("Я не знаю.")


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

"""


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


answer = ""
while answer != "Хорошо":
try:
answer = input("Как дела? ")
except KeyboardInterrupt:
print("\nПока")
break


if __name__ == "__main__":
hello_user()
23 changes: 17 additions & 6 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,23 @@

"""

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))
except (TypeError, ValueError):
return "Введены не корректные данные"

if max_discount >= 100:
raise ValueError("Слишком большая максимальная скидка")
if discount >= max_discount:
return price
else:
return price - (price * discount / 100)


if __name__ == "__main__":
print(discounted(100, 2))
print(discounted(100, "3"))
Expand Down
42 changes: 28 additions & 14 deletions 8_ephem_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,25 @@
бота отвечать, в каком созвездии сегодня находится планета.

"""
# В Setting содержится API_KEY для бота

from datetime import datetime
from typing import Type
import Setting
import logging
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')


PROXY = {
'proxy_url': 'socks5://t1.learn.python.ru:1080',
'urllib3_proxy_kwargs': {
'username': 'learn',
'password': 'python'
}
}
logging.basicConfig(
format="%(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
filename="bot.log",
)


def greet_user(update, context):
text = 'Вызван /start'
text = "Вызван /start"
print(text)
update.message.reply_text(text)

Expand All @@ -42,11 +41,26 @@ def talk_to_me(update, context):
update.message.reply_text(text)


def planet_mars(update, context):
planet = update.message.text.split()
name_planet = planet[1].lower().capitalize()
try:
planet_ephem = getattr(ephem, name_planet)(datetime.now())

constellation = ephem.constellation(planet_ephem)

text = f"Планета {name_planet} находится в {constellation}"
except AttributeError:
text = f"Планета {name_planet} не найдена."
update.message.reply_text(text)


def main():
mybot = Updater("КЛЮЧ, КОТОРЫЙ НАМ ВЫДАЛ BotFather", request_kwargs=PROXY, use_context=True)
mybot = Updater(Setting.API_KEY)

dp = mybot.dispatcher
dp.add_handler(CommandHandler("start", greet_user))
dp.add_handler(CommandHandler("planet", planet_mars))
dp.add_handler(MessageHandler(Filters.text, talk_to_me))

mybot.start_polling()
Expand Down