2014-03-13 37 views
1


我對我在Python程序中遇到的這個問題有些困惑。這是一個非常簡單的程序,但它不斷出現問題。請允許我向您展示的代碼...無法將整數轉換爲字符串

x=int(input('Enter number 1:')) 
y=int(input('Enter number 2:')) 
z=x+y 
print('Adding your numbers together gives:'+z) 

現在,這個計劃,當我運行它口口聲聲說「類型錯誤:無法轉換‘詮釋’對象隱含STR」。

我只是想讓它正常運行。 任何人都可以幫忙嗎?
謝謝。

+0

看看你'input'線,並當場明顯區別... – jonrsharpe

+0

@TomFenech這不是一個很好的副本。標題是相似的,但問題是相當不同的。 –

+0

@JohnKugelman我明白你的觀點。 –

回答

2

的問題是顯而易見的,因爲你不能連接strint。更好的方法:你可以單獨字符串和print的參數之間用逗號休息:

>>> x, y = 51, 49 
>>> z = x + y 
>>> print('Adding your numbers together gives:', z) 
Adding your numbers together gives: 100 
>>> print('x is', x, 'and y is', y) 
x is 51 and y is 49 

print功能將自動照顧變量的類型。下面的方式也能正常工作:

>>> print('Adding your numbers together gives:'+str(z)) 
Adding your numbers together gives:100 
>>> print('Adding your numbers together gives: {}'.format(z)) 
Adding your numbers together gives: 100 
>>> print('Adding your numbers together gives: %d' % z) 
Adding your numbers together gives: 100 
3

你應該重寫了最後路線爲:

print('Adding your numbers together gives:%s' % z) 

,因爲你不能使用+符號來連接一個string和Python中的int

3

您的錯誤消息告訴你到底發生了什麼事。

z是一個int而您試圖將它與一個字符串連接起來。在連接之前,您必須先將其轉換爲字符串。您可以使用str()功能做到這一點:

print('Adding your numbers together gives:' + str(z))