python:字串和數字拼接 (TypeError: Can't convert 'int' object to str implicitly)
阿新 • • 發佈:2019-01-24
我將在學習Python的路上,一路狂奔……
之前對java比較熟悉,現在開始學習python,在寫程式碼的習慣上很容易混淆兩者,今天就需要到這樣的問題,程式碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from pip._vendor.distlib.compat import raw_input
flag = False
count = 1
while flag==False and count < 4:
guess = raw_input('輸入你猜想的數字 ?')
guess = int(guess)
num = 8
if guess > num :
print ('嘿,猜大了,猜了'+count+'次')
count = count+1
elif guess == num :
print ('嘿,猜對了,猜了'+count+'次')
break
else :
print ('嘿,猜想小了,猜了'+count+'次')
count = count+1
print ('遊戲結束')
print輸出了字串和數字的拼接內容,在java的語法中這樣事被允許的,寫習慣了,也相當然的以為python這樣也可以,誰知道這樣事不可以的。在執行的時候報瞭如下的錯誤:
輸入你猜想的數字 ?9
Traceback (most recent call last):
File "D:\Workspace_myeclipse\ZwfPython\src\Test1\__init__.py", line 11, in <module>
print ('嘿,猜大了,猜了'+count+'次')
TypeError: Can't convert 'int' object to str implicitly
看最後一句,不能將int轉化成 str,一下子讓我好尷尬啊,將 print 程式碼做了如下的調整:
print ('嘿,猜想小了,猜了' +str(count)+'次')
這樣就可以順利的執行通過了,這件事讓我想到了,在不同的程式語言之間,我們雖然總是在不停地強調是相通的,但是每種語言都有自己獨樹一幟的特性。我們要慎重的看待這些特性,這也說明就是這些應運而生的特性方可以證明程式語言的進步。