2016-11-27 23 views
-1

我必須編寫一個程序,讀入一個整數並打印出數字除以2。這是我的代碼:Grok學習:減半這種類型錯誤

a= int(input("Number: ")) 
h= a/2 
print("Half number: " + h)  

但我不斷收到這個

Number: 6 
Traceback (most recent call last): 
File "program.py", line 3, in <module> 
print("Half number: " + h) 
TypeError: Can't convert 'float' object to str implicitly 

我看不出有什麼毛病我的代碼,我不知道是什麼錯誤。任何想法有什麼不對?

+1

嘗試'打印(「半數」,H)'。 – Aurora0001

+0

[TypeError:無法將'int'對象隱式轉換爲str](http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly) – Aurora0001

回答

0

表達:

"Half number: " + h 

試圖將字符串添加到浮子。您可以添加字符串到字符串:

"This string" + ", then this string" 

和浮浮:

100.0 + 16.8 

但是Python是不是願意讓你添加字符串和浮動。 (在上面的錯誤消息中,Python已經處理了第一個字符串和加法,現在它需要一個字符串 - 這就是爲什麼你會得到它不能的錯誤 - 或者至少不會 - 將一個'float '數字到字符串。)

你可以告訴Python這是你真正希望它在幾個方面做的。一種是使用內置的STR()函數的任何對象轉換爲一些合理的字符串表示,隨時可以加入到另一個字符串:

h = 100 
"You can add a string to this: " + str(h)