2013-09-22 88 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

相关问题