python的新手。我在尝试循环计算柠檬水摊位的折扣时遇到麻烦,正在处理的示例很简单
柠檬水8盎司= 1.20#无折扣
柠檬水12盎司= 1.75#(4杯或更少)
柠檬水每5杯12盎司= 1.35折扣,少于5折扣不适用。例如,如果客户购买了8个大杯子,则5个会打折,而3个不会打折。
有关如何为该问题创建函数和变量的任何帮助。我知道这是基本知识,但对python来说是新的。
答案 0 :(得分:0)
查看下面的代码和相关注释。
#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
答案 1 :(得分:0)
这是一种可能的方法:
m