2016-09-06 67 views
1

這是我的代碼。我正在做一個開始行動。當我運行程序錯誤字符串浮動

,我可以把這些值,但是當我走出循環出現以下錯誤信息:

a + = float (input ("Enter the product cost")) 

ValueError異常:無法將字符串轉換爲float:

能誰來幫幫我?

這裏有雲:

e = 0.25 
f = 0.18 
a = 0.0 

while True: 
    a += float(input("Enter the product cost: ")) 
    if a == "":   
     break 

b = a*e 
c = a*f 
d = a+b+c 

print ("tax: " + b) 
print ("tips: " + c) 
print ("Total: " + d) 
+0

你可以做'A_INPUT =浮動(輸入( 「輸入產品成本」))' –

回答

0

有幾個問題:

  1. 的是一個空字符串("")檢查來嘗試將其添加到float值之後a。你應該處理這個異常,以確保輸入是數字。
  2. 如果有人沒有輸入空字符串或無效字符串,那麼您會陷入無限循環而無法打印。這是因爲您的b, c, d計算的縮進和prints不在while循環的範圍之內。

這應該做你想要什麼:

e = 0.25 
f = 0.18 
a = 0.0 

while True: 
    try: 
     input_number = float(input("Enter the product cost: ")) 
    except ValueError: 
     print ("Input is not a valid number") 
     break 
    a += input_number   
    b = a*e 
    c = a*f 
    d = a+b+c 

    print ("tax: ", b) 
    print ("tips: ", c) 
    print ("Total: ", d) 
1

要結合在同一條線上兩個操作:一個字符串輸入到字符串到float轉換。如果輸入空字符串結束程序,則轉換爲float失敗,並顯示錯誤消息;該錯誤包含它試圖轉換的字符串,並且它是空的。

將它分成多個行:

while True: 
    inp = input("Enter the product cost: ") 
    if inp == "":   
     break 
    a += float(inp) 
+0

是不是'in'一個Python關鍵詞?也許重命名變量 – Li357

+0

@AndrewL。謝謝,那是一個愚蠢的錯誤。 –

+0

沒問題,很好的答案! – Li357