本文介绍了TypeError:无法将'int'对象转换为str隐式错误python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读了其他问题,但我试图做的事情是不同的
我试图在python中制作一个计算器,并尝试将变量输入的东西变成一个整数,这样我就可以添加它。这是我的代码,它还没有完成,我是一个初学者:
i read other questions but the thing im trying to do is differentim trying to make a calculator thingy in python and trying to make the variable input thing into a integer so i can add it. this is my code also its not finished yet and im a beginner:
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
任何帮助将不胜感激:)
any help would be appreciated :)
推荐答案
如错误信息所示,你可以将int对象添加到str对象。
As the error message say, you can't add int object to str object.
>>> 'str' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
显式转换int对象到str对象,然后连接:
Explicitly convert int object to str object, then concatenate:
>>> 'str' + str(2)
'str2'
或使用 str.format
方法:
>>> 'The answer is {}'.format(3)
'The answer is 3'
这篇关于TypeError:无法将'int'对象转换为str隐式错误python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!