请告诉我错了我的Python程序
问题描述:
尖端和税计算器
bill = price + tax + tip
price = raw_input("What is the price of the meal")
tax = price * .06
tip = price * 0.20
什么是错我的代码 我已经试过各种 请回答,并回到我请告诉我错了我的Python程序
答
几件事情。
bill = price + tax + tip #You can't add up these values BEFORE calculating them
price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing
tax = price * .06 #So here you need to do float(price) * .06
tip = price * 0.20 #And float(price) here as well.
#Then your " bill = price + tax + tip " step goes here
答
首先,你不能使用你还没有定义的变量:在你的代码的使用bill = price + tax + tip
但你的程序甚至不知道什么样的价格,税和小费还没有,所以行应该在代码的末尾,在你问价格并计算税和小费之后。
然后,你有raw_input
,这个函数返回一个字符串,如果你想将其转换为十进制数,你可以乘法和加法(浮动),您可以使用price = float(raw_input("what is the price of the meal"))
正确的,两件事情,它应该工作...
答
下面有几件事情错代码:
- 你试图计算已经定义了一些变量之前总。
-
raw_input
函数返回一个字符串,因此在将它强制为一个整数之前,您无法进行正确的数学计算。 - 在计算提示/税款时,您应该使用整数1(
1.20
)的浮动账户来计算账单的整体价值+ 20%。
下面的代码片段应该工作,你怎么想,给你一些思考如何将calculate_bill
功能自定义提示花车和自定义税彩车内的动态值传递到修饰语:
def calculate_bill(bill, bill_modifiers):
for modifier in bill_modifiers:
bill = modifier(bill)
return bill
def calculate_tip(bill, percentage=1.20):
return bill * percentage
def calculate_tax(bill, percentage=1.06):
return bill * percentage
if __name__ == '__main__':
bill = int(input("What is the price of the meal: "))
total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
print(total_bill)
'raw_input()'返回一个'string'。 – PYA
你的预期产量和实际产量是多少?还是有错误?这种情况下的错误是什么? – jacoblaw
你有什么错误?一个明显的错误是,价格,税收和小费都是在声明之前使用的。至少你可能会得到这个错误。 –