2013-09-22 142 views
5

我讀過其他問題,但我試圖做的事情不同 即時嘗試在python中製作計算器thingy並嘗試將可變輸入內容一個整數,所以我可以添加它。這是我的代碼也是其尚未完成和IM初學者:TypeError:不能將'int'對象隱式轉換爲str python

print("Hello! Whats your name?") 
myName = input() 
print("What do you want me to do? " + myName) 
print("I can add, subtract, multiply and divide.") 
option = input('I want you to ') 
if option == 'add': 
    print('Enter a number.') 
    firstNumber = input() 
    firstNumber = int(firstNumber) 

    print('Enter another number.') 
    secondNumber = input() 
    secondNumber = int(secondNumber) 

    answer = firstNumber + secondNumber 

    print('The answer is ' + answer) 

它做什麼:

Hello! Whats your name? 
Jason 
What do you want me to do? Jason 
I can add, subtract, multiply and divide. 
I want you to add 
Enter a number. 
1 
Enter another number. 
1 
Traceback (most recent call last): 
File "C:/Python33/calculator.py", line 17, in <module> 
print('The answer is ' + answer) 
TypeError: Can't convert 'int' object to str implicitly 

任何幫助,將不勝感激:)

回答

3

由於錯誤消息說,你不能將int對象添加到str對象。

>>> 'str' + 2 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Can't convert 'int' object to str implicitly 

明確int對象轉換爲海峽對象,然後拼接:

>>> 'str' + str(2) 
'str2' 

或者使用str.format方法:

>>> 'The answer is {}'.format(3) 
'The answer is 3' 
+1

你也可以在使用逗號,而不是'+'的' print'函數,因爲它會自動將任何非字符串參數轉換爲'str'。 – Blckknght

+1

我認爲你幫了我:)是我應該讓它打印('答案是{。'。format(answer))? – soupuhman

+1

@soupuhman,是的,您可以按照Blckknght的說法,'print('答案是'format。(答案))'或'print('答案是',答案)'。 – falsetru

相關問題