2012-11-03 39 views
3

的非INT我寫了一個簡單的程序來計算稅收的一些電氣部件乘序列,它是這樣的:爲什麼我收到錯誤不能按類型「浮動」 PYTHON

print "How much does it cost?",  
price = raw_input()  
print "Tax: %s" % (price * 0.25)  
print "Price including tax: %s" % (price * 1.25)  
raw_input ("Press ENTER to exit") 

我不斷收到此錯誤:

Traceback (most recent call last): 
    File "moms.py", line 3, in <module> 
    print "Tax: %s" % (price * 0.25) 
TypeError: can't multiply sequence by non-int of type 'float' 

回答

1

這意味着price不是一個數字。事實上,這是一個字符串,因爲這就是raw_input的回報。您需要使用float解析它,或使用input而不是raw_input

1

基本上你不能用一個浮點數也許乘以一個字符串,你要啥子是

price = float(raw_input()) 
1

您需要至由raw_input()返回到float第一字符串轉換:

price = float(raw_input("How much does it cost?")) # no need for extra print 
+0

感謝大家的支持,現在工作。感謝您的幫助 –

+0

@ user1796426如果這回答了您的問題,最好點擊選項下的勾號(✔)以[接受答案](http://meta.stackexchange.com/a/5235)而不是發帖感謝評論。 –

1

price是一個字符串。你需要從你輸入的字符串中創建一個浮點數:

>>> price_str = raw_input() 
123.234 
>>> print type(price) 
<type 'str'> 
>>> price = float(price_str) 
>>> print type(price) 
<type 'float'> 
>>> print "Tax: %s" % (price * 0.25) 
Tax: 30.8085 
>>> 
相關問題