难以满足具有特定需求(python)的小费税计算器的逻辑

时间:2018-09-13 20:42:10

标签: python python-3.x

我正在为学校编写一个具有以下参数的程序:

编写一个程序,该程序将计算进餐价格的XXX%小费和6%税。用户将输入餐食价格,程序将计算小费,税金和总额。总计为餐费加上小费加上税金。然后,您的程序将显示小费,税金和总计的值。

餐厅现在希望更改程序,以使小费百分比基于餐费价格。新金额如下:

Meal Price Range       Tip Percent
.01 to 5.99            10%
6 to 12.00             13%
12.01 to 17.00         16%
17.01 to 25.00         19%
25.01 and more         22%

到目前为止,这是我的代码:

def main():

#variables for calculating tip

a = .10
b = .13
c = .16
d = .19
e = .22

#variable for calculating tax

tax = .06

#variable for user input

user = 0.0
total = 0.0

#get user input

user = float(input("Please input the cost of the meal "))

if user > .01 and user < 5.99:

从这里开始,我在获取用户输入并计算user * tax + user = total方面一直没有成功。那应该给我我的计算,但是我应该如何实现它。这是在Python 3.6 IDLE上。

3 个答案:

答案 0 :(得分:2)

在此行之后,您要执行逻辑:

if user < .01 and user > 5.99:

(我假设这应该是总计在$ 0.01和$ 5.99之间) 因此,示例如下所示:

if user > .01 and user <= 5.99:
    print("Total is: " + str((user*tax)*a))
elif user > 5.99 and user <= 12.00:
    print("Total is: " + str((user*tax)*b))

答案 1 :(得分:1)

您可以定义一个基于用餐价格设置的tip变量。

user = float(input("Please input the cost of the meal "))
tip = 0 # we'll overwrite this
if user > .01 and user < 5.99:
  tip = 0.1
elif user > 5.99 and user < 12:
  tip = 0.13
# etc, until...
else:
    # at this point user should be >= 25.01
    tip = 0.22

然后找到实际的提示“价格”,并将其添加到总计中:

tip_price = user * tip
total += tip_price # note that you must still add tax and baseline price

答案 2 :(得分:1)

您需要:

import numpy as np
def price(x):
    if x<=0: return 0
    tax = 0.06
    a = np.array([0.01, 6, 12.01, 17.01, 25.01])
    b = np.array([10, 13, 16, 19, 22])/100
    tip = dict(zip(a, b)).get(a[(x>=a).sum()-1] , 0)
    return round(x * (1 + tax ) + tip,3)   

对于价格5,我们有5+(5*0.06) +0.1 = 5.4的价格为17,然后为17+(17*0.06) +0.16=18.1830+(30*0.06) +0.22=32.02: 现在调用我们的price函数:

 price(5)
Out[745]: 5.4

price(17)
Out[746]: 18.18

price(30)
Out[747]: 32.02