2014-10-09 70 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