用户输入产生“不能将序列乘以'int'类型的非int”

时间:2017-07-02 22:36:08

标签: python python-3.x

我是初学者以及使用Python编程,我目前正在使用代码学院来帮助我学习。所以我决定冒险尝试自己创建一个程序并继续遇到错误消息:不能将序列乘以'float'类型的非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 个答案:

答案 0 :(得分:0)

你忘记将str转换为float:

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)

答案 1 :(得分:0)

您的问题是您使用input()raw_input()混合使用。这是初学者常犯的错误。 input()将您的代码评估为Python表达式并返回结果。 raw_input()但是,只需输入并将其作为字符串返回。

所以当你这样做时:

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()将提示作为字符串,并将输入转换为浮点数:

#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)