2014-10-09 71 views
-1

我试图转换其值改变的变量,但是该值通常是一位小数,例如0.5。我试图将此变量更改为0.50。我使用这个代码,但是当我运行该程序,它说TypeError: Can't convert 'float' object to str implicitly将浮点型变量转换为字符串

这里是我的代码:

while topup == 2: 
    credit = credit + 0.5 
    credit = str(credit) 
    credit = '%.2f' % credit 
    print("You now have this much credit £", credit) 
    vending(credit) 
+0

这不是我得到的错误。你使用的是什么版本的Python? – Kevin 2014-10-09 17:45:39

+0

错误实际上是你在''%.2f'%credit'中传递一个字符串TypeError:需要一个float,并且需要'TypeError:float参数,而不是str',用于python 2. – 2014-10-09 17:49:24

+0

@凯文我正在使用Python 3.4 – NoobProgrammer 2014-10-09 17:53:42

回答

1
while topup == 2: 
    credit = float(credit) + 0.5 
    credit = '%.2f' % credit 
    print("You now have this much credit £", credit) 
    vending(credit) 

问题是你不能浮动格式的字符串

"%0.2f"%"3.45" # raises error 

相反,它期望一个号码

"%0.2f"%3.45 # 0k 
"%0.2f"%5 # also ok 

所以当你调用str(credit)它打破了格式字符串正下方(即偶然也蒙上信贷返回一个字符串)

顺便说一句,你真的应该只有当你在一般的打印

credit = 1234.3 
print("You Have : £%0.2f"%credit) 

你要做到这一点你的荣誉是一个数字类型,以便你可以用它做数学

+0

有没有反正我可以通过不使用str(信用)以任何其他方式解决我的问题? – NoobProgrammer 2014-10-09 17:51:18

+1

没有理由使用'str(credit)' – 2014-10-09 17:55:15