-
Notifications
You must be signed in to change notification settings - Fork 462
/
Copy path7_exception2.py
61 lines (49 loc) · 2.09 KB
/
7_exception2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Домашнее задание №1
Исключения: приведение типов
* Перепишите функцию discounted(price, discount, max_discount=20)
из урока про функции так, чтобы она перехватывала исключения,
когда переданы некорректные аргументы.
* Первые два нужно приводить к вещественному числу при помощи float(),
а третий - к целому при помощи int() и перехватывать исключения
ValueError и TypeError, если приведение типов не сработало.
"""
stock = [
{'name': 'iPhone 12', 'stock': 24, 'price': 65432,
'discount': 25},
{'name': 'Samsung Galaxy S21', 'stock': 8, 'price': 50000,
'discount': 10},
{'name': '', 'stock': 18, 'price': 10000,
'discount': 10}
]
def discounted(price, discount, max_discount=20, phone_name=''):
try:
price = float(price)
discount = float(discount)
max_discount = int(max_discount)
except(ValueError, TypeError):
print('Ошибка в типе аргумента')
return None
price = abs(price)
discount = abs(discount)
max_discount = abs(max_discount)
if max_discount >= 100:
raise ValueError('Максимальная скидка не должна быть больше 100')
if discount >= max_discount:
return price
elif 'iphone' in phone_name.lower() or not phone_name:
return price
else:
return price - (price * discount / 100)
for phone in stock:
price_final = discounted(phone['price'], phone['discount'], phone_name=phone('name'))
if price_final is not None:
phone['price_final'] = price_final
else:
print('Ошибка в расчетах')
print(discounted(100, 2))
print(discounted(100, "3"))
print(discounted("100", "4.5"))
print(discounted("five", 5))
print(discounted("сто", "десять"))
print(discounted(100.0, 5, "10"))