2017-05-08 26 views
0

我正在來回奔波,並將自己搞砸在這段代碼上。我有一個公式來計算總膳食價格。使用for循環根據一系列提示百分比計算膳食價格

def total_cost(price,tax,tip): 

    bill = price+(price*tax)+((price+(price*tax))*tip) 
    return bill 

new_bill = total_cost(15,.08875,.18) 

print(new_bill) 

從那裏,我怎麼寫一個for循環,計算一餐的總價格,對於不同的臨界率,從15%開始,以1%的增量在25%(包括兩端)的結局?

+0

爲什麼代碼被刪除? – tdelaney

回答

2

你只需要循環百分比:

for tip in range(15, 26, 1): # the end point is exclusive with "range" 
    cost = total_cost(15, 0.08875, tip/100.) # in python3 you could use tip/100 
    print(cost) 
1

超級簡單,但是這將是第一關:

tips = list(range(15, 26)) 

for tip in tips: 
    print("For " + str(tip) + "% the total cost is $" + str(total_cost(price, tax, tip/100)) 

或者for循環可能是:

for tip in range(15, 26, 1): 

...保存一點點內存。

+0

你確定'範圍(0.15,0.26,0.01)'不會拋出'TypeError:range()整數結束參數的預期,獲得浮動。它在我的電腦上這樣做。 – MSeifert

+0

是的,範圍只是整數。第一次過關傾向於希望某些事情以某種方式工作。 –

+0

我完全同意「希望某些事情以某種方式工作」! :) – MSeifert

1

一行溶液:

print list(total_cost(15, 0.08875, tip/100.) for tip in range(15, 26)) 

在最外括號中的部分是一個發生器 - 它不執行任何本身,因爲它僅是一個算法

功能list()強制它工作。