2012-12-20 163 views
2

嗨我是新來的蟒蛇,我正在練習通過一個簡單的計算器。 該方案可以讓我輸入數值爲一頓,稅和小費但這樣做的計算,當我得到這個錯誤:簡單的Python計算器

Traceback (most recent call last): 
    File "C:/Users/chacha04231991/Desktop/pytuts/mealcost.py", line 5, in <module> 
    meal = meal + meal * tax 
TypeError: can't multiply sequence by non-int of type 'str' 

的是代碼:

meal = raw_input('Enter meal cost: ') 
tax = raw_input('Enter tax price in decimal #: ') 
tip = raw_input('Enter tip amount in decimal #: ') 

meal = meal + meal * tax 
meal = meal + meal * tip 

total = meal 
print 'your meal total is ', total 
+2

'raw_input'的結果是'str'。 – alexvassel

回答

1

你需要轉換你的輸入從字符串到數字,例如整數:

meal = int(raw_input('Enter meal cost: ')) 
tax = int(raw_input('Enter tax price in decimal #: ')) 
tip = int(raw_input('Enter tip amount in decimal #: ')) 

如果您需要輸入小數金額,也可以使用decimal類型。

from decimal import Decimal 
meal = Decimal(raw_input('Enter meal cost: ')) 
tax = Decimal(raw_input('Enter tax price in decimal #: ')) 
tip = Decimal(raw_input('Enter tip amount in decimal #: ')) 

我會建議你不要爲此使用浮點數,因爲它會給舍入誤差。

+0

它工作正常使用浮動,但當我嘗試十進制是給這個錯誤:追溯(最近呼籲最後): 文件「C:/Users/chacha04231991/Desktop/pytuts/mealcost.py」,第4行,在 稅=十進制(raw_input('以十進制數字輸入稅價):) NameError:未定義名稱'decimal' – codeYah

+0

@codeYah:帶有小d的'decimal'是模塊的名稱。 「Decimal」類型具有大寫字母「D」。 –

1

當您使用的raw_input,你得到的輸入型str

>>> meal = raw_input('Enter meal cost: ') 
Enter meal cost: 5 
>>> type(meal) 
<type 'str'> 

你應該執行行爲

>>> meal = int(raw_input('Enter meal cost: ')) 
Enter meal cost: 5 
>>> type(meal) 
<type 'int'>