Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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

32 changes: 28 additions & 4 deletions 1_if1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,46 @@

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

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

"""


def define_occupation_by_age(age: int) -> 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 isinstance(string_1, str) or not isinstance(string_2, str):
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()
47 changes: 44 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,53 @@
* Посчитать и вывести среднее количество продаж всех товаров
"""

sales = [
{'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 product_sales(product):
return sum(product["items_sold"])


def product_sale_times(product):
return len(product["items_sold"])


def total_sales(sales_dict):
return sum([product_sales(product) for product in sales_dict])


def total_sale_times(sales_dict):
total_sales_times = sum([product_sale_times(product) for product in sales_dict])
return total_sales_times


def avg_sale(sales, sale_times):
return round(sales/sale_times)


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


print('1. Суммарное количество продаж по товарам:')
for product in sales:
print(f'\t{product["product"]}: {product_sales(product)}')

print('\n2. Среднее количество продаж по товарам:')
for product in sales:
print(f'\t{product["product"]}: {avg_sale(product_sales(product), product_sale_times(product))}')

print(f'\n3. Cуммарное количество продаж всех товаров: {total_sales(sales)}')

print(f'\n4. Cреднее количество продаж всех товаров: '
f'{avg_sale(total_sales(sales), total_sale_times(sales))}')


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()
63 changes: 56 additions & 7 deletions 7_exception2.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,64 @@
* Первые два нужно приводить к вещественному числу при помощи float(),
а третий - к целому при помощи int() и перехватывать исключения
ValueError и TypeError, если приведение типов не сработало.

"""
import traceback


# Вариант 1 (получение информации о переменной, которая передана неверно, из 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)
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}'

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


# Вариант 2 (как надо делать)
def discounted(price, discount, max_discount=20):
error_message = 'Неверное значение переменной'
expected_exceptions = (ValueError, TypeError)

try:
price = float(price)
except expected_exceptions:
return f'{error_message} price'

try:
discount = float(discount)
except expected_exceptions:
return f'{error_message} discount'

try:
max_discount = int(max_discount)
except expected_exceptions:
return f'{error_message} max_discount'

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


def discounted(price, discount, max_discount=20)
"""
Замените pass на ваш код
"""
pass

if __name__ == "__main__":
print(discounted(100, 2))
print(discounted(100, "3"))
Expand Down
Loading