TypeError:/:'type'和'float'的不支持的操作数类型

时间:2013-05-29 01:35:19

标签: python

我想得到成本的输入。成本除以.65并将答案输出为列表。

cost = int                                                                  
raw_input('What is the cost:  ')
print 'list = ',   cost  /.65

已尝试int(cost) --- float(cost) int('cost') - input而不是raw_input

任何帮助都将不胜感激。

参加了许多python教程,但无法理解解决方案。

2 个答案:

答案 0 :(得分:1)

您刚刚将类型对象int分配给变量cost。可能是您尝试将数据类型分配给变量cost,就像我们在C中一样,但这在python中不是必需的。

  

cost = int

您询问了用户输入但未将返回值分配给任何变量,因此该值实际上已丢失。

  

raw_input('费用是多少'')

当您尝试将类型对象(int)除以浮动时,这会引发错误。

  

print'list =',cost /.65

一个简单的解决方案:

#get input from user, the returned value will be saved in the variable cost.
cost = raw_input('What is the cost:  ')  

# convert cost to a float as raw_input returns a string, float 
# is going to be more appropriate for money related calculations than an integer
cost_fl = float(cost)  

#use string formatting 
print 'list = {}$'.format(cost_fl /.65)

答案 1 :(得分:0)

另一种方式:

while True:
    try:
        cost=float(raw_input('What is the cost: '))
        break
    except ValueError:
        print "Can't understand your input. Try again please." 
        continue

print 'list=${:.2f}'.format(cost/.65) 

如果你运行:

What is the cost: rr
Can't understand your input. Try again please.
What is the cost: 5.67
list=$8.72

如果输入try / except,则会过滤掉用户输入错误。