Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,7 @@ dmypy.json

# Pyre type checker
.pyre/

.idea/
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше вносить это в .gitignore и не коммитить

settings.py

34 changes: 30 additions & 4 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,48 @@

Условный оператор: Возраст

* Попросить пользователя ввести возраст при помощи input и положить
* Попросить пользователя ввести возраст при помощи input и положить
результат в переменную
* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь:
* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь:
учиться в детском саду, школе, ВУЗе или работать
* Вызвать функцию, передав ей возраст пользователя и положить результат
* Вызвать функцию, передав ей возраст пользователя и положить результат
работы функции в переменную
* Вывести содержимое переменной на экран

"""

from typing import Optional
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯👌



def define_occupation_by_age(age: int) -> Optional[str]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C точки зрения типизации, функция все еще возвращает Optional, потому что при возрасте больше 120 вернет None
Убери проверку на верхнюю границу (и нижнюю).
Сигнатура функции (age: int) -> str: означает что такая функция для любого инта вернет некоторую строку.
Так как ты проверяешь возраст на интервал 0-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)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь все равно ты не обрабатывешь None

print(f'Ожидается, что в этом возрасте человек должен {user_expected_occupation}')


if __name__ == "__main__":
main()
29 changes: 21 additions & 8 deletions 2_if2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]):
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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()
30 changes: 27 additions & 3 deletions 3_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]},
]
Expand All @@ -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:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

разбей решение на несколько функций
print только снаружи функций оставь

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()
14 changes: 7 additions & 7 deletions 4_while1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@

Цикл while: hello_user

* Напишите функцию hello_user(), которая с помощью функции input() спрашивает
* Напишите функцию hello_user(), которая с помощью функции input() спрашивает
пользователя “Как дела?”, пока он не ответит “Хорошо”

"""


def hello_user():
"""
Замените pass на ваш код
"""
pass
while True:
user_response = input('Как дела? ')
if user_response == 'Хорошо':
break



if __name__ == "__main__":
hello_user()
21 changes: 14 additions & 7 deletions 5_while2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,23 @@

Пользователь: Что делаешь?
Программа: Программирую

"""
import datetime

questions_and_answers = {
'Как дела?': 'Хорошо!',
'Что делаешь?': 'Программирую',
'Пойдём гулять?': 'Пойдём',
'Сколько время?': datetime.datetime.now()
}

questions_and_answers = {}

def ask_user(answers_dict):
"""
Замените pass на ваш код
"""
pass
while True:
user_question = input('Введите вопрос: ')
print(answers_dict.get(user_question, 'не знаю'))


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

Исключения: KeyboardInterrupt

* Перепишите функцию hello_user() из задания while1, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
* Перепишите функцию hello_user() из задания while1, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
и завершала работу при помощи оператора break

"""


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

try:
while True:
user_response = input('Как дела? ')
if user_response == 'Хорошо':
break
except KeyboardInterrupt:
print('\nПока')


if __name__ == "__main__":
hello_user()
33 changes: 26 additions & 7 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,34 @@
* Первые два нужно приводить к вещественному числу при помощи float(),
а третий - к целому при помощи int() и перехватывать исключения
ValueError и TypeError, если приведение типов не сработало.

"""
import traceback


def discounted(price, discount, max_discount=20):
try:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В try должно быть как можно меньше кода, здесь ты пытаешься перехватить всех , и потом в обработке исключения пытаешься понять что же все таки происходило.
Сделай по отдельному try-catch на price, discount & max_discount

price = float(price)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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('Слишком большая максимальная скидка')
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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"))
Expand Down
56 changes: 38 additions & 18 deletions 8_ephem_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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()

Expand Down