2017-07-02 40 views
2

的非INT繁衍序列我在这里是初学者,以及在Python编程,和我目前使用的代码学院帮助我学习。所以我决定冒险离开,自己做一个程序,并继续陷入错误信息:无法乘以类型为'float'的非int int序列也能收到错误消息:无法按类型“浮动”

该程序非常简单,一个小费计算器要求用户输入信息以使程序确定小费金额和账单总额。直到数学的这一点才确定。我知道这不是“漂亮”,但只是我真的想弄清楚如何使用它。任何帮助将不胜感激!

这是我到目前为止有:

print ("Restuarant Bill Calculator") 
print ("Instructions: Please use only dollar amount with decimal.") 

# ask the user to input the total of the bill 
original = raw_input ('What was the total of your bill?:') 
cost = original 
print (cost) 

# ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print "%.2f" % tipamt 

# doing the math 
totalamt = cost + tipamt 
print (totalamt) 
+2

请添加完整的错误消息完全错误的路线。更一般地说,请阅读[mcve]和[问]。 (你可能想乘以一个浮动的字符串) –

回答

1

这似乎从你的代码,你使用python2。在python2中,接收用户输入的函数是raw_input。不要使用input功能,当你在python2接受用户数据,因为它会自动尝试eval它,这是dangerous

作为抬头:在python3中,函数是input,并且没有raw_input。现在

,你原来的问题,你需要强制转换的值输入函数返回,因为它是作为字符串返回。

所以,你需要:

... 
cost = float(original) 
... 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost 
... 

这应该工作。

+1

哈哈不错,只是在时间:) –

+0

“*在python3,功能输入,没有*的raw_input” < - 那种回答您的第一个问题,不是吗? –

+0

@AndrasDeak哈哈,思维过程往往会演变为后写入。 –

0

你忘了给STR转化为浮动:

original = raw_input('What was the total of your bill?:') 
cost = float(original) 
print (cost) 

#ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print("%.2f" % tipamt) 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
0

你的问题是,你正在使用input()混合raw_input()。这是初学者常犯的错误。 input()评论你的代码,就好像它是一个Python表达式并返回结果。但是,只需获取输入并将其作为字符串返回。

所以,当你这样做:

tip * cost 

你真正做的是一样的东西:

2.5 * '20' 

这当然,是没有意义和Python会引发一个错误:

>>> 2.5 * '20' 
Traceback (most recent call last): 
    File "<pyshell#108>", line 1, in <module> 
    '20' * 2.5 
TypeError: can't multiply sequence by non-int of type 'float' 
>>> 

首先,您需要使用raw_input()获得成本,那么强制转换为整数。然后使用taw_input()获得尖端作为一个字符串,并投输入到一个float:

#ask the user to input the total of the bill 

# cast input to an integer first! 
original = int(raw_input('What was the total of your bill?:')) 
cost = original 
print (cost) 

#ask the user to put in how much tip they want to give 

# cast the input to a float first! 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost  
print "%.2f" % tipamt 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
相关问题