Новое в питоне. У меня возникли проблемы с попыткой сделать цикл для расчета скидки на киоск с лимонадом, пример, над которым я работаю, прост
лимонад 8oz = 1.20 #без скидки
лимонад 12 унций = 1,75 # за 4 и меньше чашек
лимонад 12 унций = скидка 1,35 за каждые 5 чашек, меньше 5-ти скидка не распространяется. Например, если клиент покупает 8 больших чашек, скидка будет на 5, а на 3 — нет.
Любая помощь в том, как сделать функцию и переменную для этой проблемы. Я знаю, что это просто, но я новичок в python.
Проверьте мой ответ ниже!
Ознакомьтесь с приведенным ниже кодом и соответствующими комментариями.
#Lemonade prices variables
price_8oz = 1.2
price_12oz_without_discount = 1.75
price_12oz_discount = 1.35
#Function to calculate price
def price(no_8oz, no_12oz):
#Total price of 8 oz is price multiplied by no of 8oz cups
total_price_8oz = price_8oz*no_8oz
#Number of 12oz without discount is the remainder after dividing by 5
num_12oz_cups_without_discount = no_12oz%5
#Number of 12oz with discount is total cups minus number of 12oz cups without discount
num_12oz_cups_with_discount = no_12oz - num_12oz_cups_without_discount
#Total price for 12oz cups
total_price_12oz = num_12oz_cups_without_discount*price_12oz_without_discount + num_12oz_cups_with_discount*price_12oz_discount
#Total price for all lemonades
total_price = total_price_8oz + total_price_12oz
return total_price
print(price(5, 5))
# 5*1.2 + 5*1.35 = 12.75
print(price(5, 4))
# 5*1.2 + 4*1.75 = 13.0
print(price(5, 14))
# 5*1.2 + 10*1.35 + 4*1.75 = 26.5
Спасибо Девеш и Фурас.
Вот возможный подход:
def discount(size, count):
price_8oz = 1.20
price_12oz = 1.75
price_12oz_discount = 1.35
if size == 8:
return price_8oz * count
elif size == 12:
if count <= 4:
return price_12oz * count
elif count > 4:
# divmod() divides one number by another and returns both the number of times
# the second number fits into the first, but also the remainder.
# Here we calculate how many times five goes into the customer order
# and how many extra cups are left over.
fivecount, remainder = divmod(count, 5)
return price_12oz_discount * fivecount * 5 + 1.75 * remainder
# Here we test the code to make sure that it works across several iterations of five counts
# with 12 ounce cups.
for count in range(2, 12):
print('count:', count, 'cost:', discount(12, count))
8 % 5 = 3
так что у вас есть чашки без скидки.(8 // 5) * 5 = 5
так что у вас есть чашки со скидкой. То же самое на 12 больших чашек -12 % 5 = 2
без скидки,(12 // 5) * 5 = 10
со скидкой. Или если у вас есть12 % 5 = 2
без скидки, то у вас есть12 - 2 = 10
со скидкой.