TypeError: Can't convert 'int' object to str implicitly error python
本问题已经有最佳答案,请猛点这里访问。
我读过其他问题,但我想做的是不同的我试着用python编写一个计算器,并试着将变量输入变成一个整数,这样我就可以添加它了。这是我的代码,它还没有完成,我是一个初学者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) |
它的作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
号
如有任何帮助,我们将不胜感激:)
正如错误消息所说,不能向str对象添加int对象。
1 2 3 4 | >>> 'str' + 2 Traceback (most recent call last): File"<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly |
显式将int对象转换为str对象,然后连接:
1 2 | >>> 'str' + str(2) 'str2' |
号
或采用
1 2 | >>> 'The answer is {}'.format(3) 'The answer is 3' |