TypeError:不能将序列乘以'float'类型的非int,即使已经用float()解析

Dod*_*cin 2 python

# -*- coding: UTF-8 -*-
#1 kilogram : 2.205 pounds = x : y
#from __future__ import division

z=0

print "****The nicest kilos to pounds converter on Earth****"
while z==0:
    select=input("1)Kilos to pounds\n2)Pounds to kilos\n")
    if select==1:
        y=float(raw_input('Kilos: '))
        print "Is %f pounds\n" % y*2.205
        z=int(raw_input('Exit? [0/1] '))
    elif select==2:
        y=float(raw_input('Pounds: '))
        print "Is %f kilos\n" % y/2.205
        z=int(raw_input('Exit? [0/1] '))

print "Bye Bye!"
Run Code Online (Sandbox Code Playgroud)

为什么我一直得到TypeError:不能将序列乘以'float'类型的非int?在捕获输入后,y是否已经转换为浮动?我真的找不到这段代码的错误.

Mar*_*ers 5

首先插入字符串,然后乘以结果:

>>> y = 2.5
>>> "Is %f pounds\n" % y*2.205
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为%运算符具有与乘法相等的运算符优先级,并且在这种情况下运算符从左向右执行.

在乘法周围加上括号:

>>> "Is %f pounds\n" % (y*2.205)
'Is 5.512500 pounds\n'
Run Code Online (Sandbox Code Playgroud)

为您的部门做同样的事情:

print "Is %f kilos\n" % (y/2.205)
Run Code Online (Sandbox Code Playgroud)

或者,用于str.format()格式化您的值:

print "Is {:f} pounds\n".format(y * 2.205)
Run Code Online (Sandbox Code Playgroud)

print "Is {:f} kilos\n".format(y / 2.205)
Run Code Online (Sandbox Code Playgroud)