-
Notifications
You must be signed in to change notification settings - Fork 467
Alexandra Poturaeva #137
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
base: master
Are you sure you want to change the base?
Alexandra Poturaeva #137
Changes from all 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 |
|---|---|---|
|
|
@@ -121,3 +121,7 @@ dmypy.json | |
|
|
||
| # Pyre type checker | ||
| .pyre/ | ||
|
|
||
| .idea/ | ||
| settings.py | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,22 +4,46 @@ | |
|
|
||
| Условный оператор: Возраст | ||
|
|
||
| * Попросить пользователя ввести возраст при помощи input и положить | ||
| * Попросить пользователя ввести возраст при помощи input и положить | ||
| результат в переменную | ||
| * Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: | ||
| * Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: | ||
| учиться в детском саду, школе, ВУЗе или работать | ||
| * Вызвать функцию, передав ей возраст пользователя и положить результат | ||
| * Вызвать функцию, передав ей возраст пользователя и положить результат | ||
| работы функции в переменную | ||
| * Вывести содержимое переменной на экран | ||
|
|
||
| """ | ||
|
|
||
|
|
||
| def define_occupation_by_age(age: int) -> str: | ||
| """ | ||
| Function get user age and define their expected occupation | ||
| """ | ||
| if age < 7: | ||
| return 'учиться в детском саду' | ||
| elif 7 <= age < 17: | ||
| return 'учиться в школе' | ||
| elif 17 <= age < 24: | ||
| return 'учиться в ВУЗе' | ||
| elif 24 <= age < 65: | ||
| return 'работать' | ||
| elif 65 <= age: | ||
| 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) | ||
|
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. здесь все равно ты не обрабатывешь None |
||
| print(f'Ожидается, что в этом возрасте человек должен {user_expected_occupation}') | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,15 +10,64 @@ | |
| * Первые два нужно приводить к вещественному числу при помощи float(), | ||
| а третий - к целому при помощи int() и перехватывать исключения | ||
| ValueError и TypeError, если приведение типов не сработало. | ||
| """ | ||
| import traceback | ||
|
|
||
|
|
||
| # Вариант 1 (получение информации о переменной, которая передана неверно, из traceback) | ||
| def discounted(price, discount, max_discount=20): | ||
| try: | ||
|
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. В try должно быть как можно меньше кода, здесь ты пытаешься перехватить всех , и потом в обработке исключения пытаешься понять что же все таки происходило. |
||
| price = float(price) | ||
|
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. Все еще не обернуты по одному |
||
| discount = float(discount) | ||
| max_discount = int(max_discount) | ||
| except ValueError: | ||
| traceback_split = traceback.format_exc().split() | ||
|
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 var in discounted.__code__.co_varnames[:2]: | ||
| if var in traceback_split: | ||
| return f'Неверное значение переменной {var}' | ||
| except TypeError: | ||
| traceback_split = traceback.format_exc().split() | ||
|
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 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")) | ||
|
|
||
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.
Лучше вносить это в .gitignore и не коммитить