2017-08-03 21 views
-2

不知道爲什麼,但這個簡單的Python代碼是給我的錯誤:簡單的Python打印命令給予不支持的類型錯誤

''' 
Created on Aug 2, 2017 

@author: Justin 
''' 

x = int(input("Give me a number, now.....")) 
if x % 2 != 0: 
    print(x + " is an odd number!") 
else: 
    print(x + " is an even number!") 

錯誤是說:

Traceback (most recent call last): 

    File "C:\Users\Justin\Desktop\Developer\Eclipse Java Projects\PyDev Tutorial\src\Main\MainPy.py", line 9, in <module> 

    print(x + " is an odd number!") 

TypeError: unsupported operand type(s) for +: 'int' and 'str' 

請幫幫忙!

謝謝!

+2

錯誤消息說,這一切:你想加在一起一個int和一個字符串。這是行不通的。將int轉換爲字符串,然後將它們加在一起 –

回答

1

打印時需要將x轉換爲str

print(str(x) + " is an odd number!") 

或者你可以更好的使用formatting

print('{} is an odd number'.format(x)) 
0

您可以將整數添加到字符串。但是,您可以將字符串添加到字符串中。鑄造X爲字符串添加之前:

print(str(x) + " is an odd number!") 
0

您可以連接字符串+字符串沒有字符串+ INT

在你的代碼

X爲int類型,所以你可以不加直接與字符串,你必須轉換成字符串海峽關鍵字

x = int(input("Give me a number, now.....")) 

if x % 2 != 0: 
    print(str(x) + " is an odd number!") 
else: 
    print(str(x) + " is an even number!") 
+0

你試過這個嗎? – ksai

0

ÿ你需要將字符串連接成字符串。但x是,所以你需要把它轉換成字符串串連之前的整...低於連擊方法使用...... 試試這個,

print("{} is an odd number!".format(x)) 
0

您需要int轉換爲str

你最好在Python中使用新的格式:

print("{} is an odd number!".format(x)) 
相關問題