2017-07-02 44 views
2

的非INT繁衍序列我在這裏是初學者,以及在Python編程,和我目前使用的代碼學院幫助我學習。所以我決定冒險離開,自己做一個程序,並繼續陷入錯誤信息:無法乘以類型爲'float'的非int int序列也能收到錯誤消息:無法按類型「浮動」

該程序非常簡單,一個小費計算器要求用戶輸入信息以使程序確定小費金額和賬單總額。直到數學的這一點才確定。我知道這不是「漂亮」,但只是我真的想弄清楚如何使用它。任何幫助將不勝感激!

這是我到目前爲止有:

print ("Restuarant Bill Calculator") 
print ("Instructions: Please use only dollar amount with decimal.") 

# ask the user to input the total of the bill 
original = raw_input ('What was the total of your bill?:') 
cost = original 
print (cost) 

# ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print "%.2f" % tipamt 

# doing the math 
totalamt = cost + tipamt 
print (totalamt) 
+2

請添加完整的錯誤消息完全錯誤的路線。更一般地說,請閱讀[mcve]和[問]。 (你可能想乘以一個浮動的字符串) –

回答

1

這似乎從你的代碼,你使用python2。在python2中,接收用戶輸入的函數是raw_input。不要使用input功能,當你在python2接受用戶數據,因爲它會自動嘗試eval它,這是dangerous

作爲擡頭:在python3中,函數是input,並且沒有raw_input。現在

,你原來的問題,你需要強制轉換的值輸入函數返回,因爲它是作爲字符串返回。

所以,你需要:

... 
cost = float(original) 
... 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost 
... 

這應該工作。

+1

哈哈不錯,只是在時間:) –

+0

「*在python3,功能輸入,沒有*的raw_input」 < - 那種回答您的第一個問題,不是嗎? –

+0

@AndrasDeak哈哈,思維過程往往會演變爲後寫入。 –

0

你忘了給STR轉化爲浮動:

original = raw_input('What was the total of your bill?:') 
cost = float(original) 
print (cost) 

#ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print("%.2f" % tipamt) 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
0

你的問題是,你正在使用input()混合raw_input()。這是初學者常犯的錯誤。 input()評論你的代碼,就好像它是一個Python表達式並返回結果。但是,只需獲取輸入並將其作爲字符串返回。

所以,當你這樣做:

tip * cost 

你真正做的是一樣的東西:

2.5 * '20' 

這當然,是沒有意義和Python會引發一個錯誤:

>>> 2.5 * '20' 
Traceback (most recent call last): 
    File "<pyshell#108>", line 1, in <module> 
    '20' * 2.5 
TypeError: can't multiply sequence by non-int of type 'float' 
>>> 

首先,您需要使用raw_input()獲得成本,那麼強制轉換爲整數。然後使用taw_input()獲得尖端作爲一個字符串,並投輸入到一個float:

#ask the user to input the total of the bill 

# cast input to an integer first! 
original = int(raw_input('What was the total of your bill?:')) 
cost = original 
print (cost) 

#ask the user to put in how much tip they want to give 

# cast the input to a float first! 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost  
print "%.2f" % tipamt 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
相關問題