【问题标题】:TypeError: Can't convert 'int' object to str implicitly error python [duplicate]TypeError:无法将'int'对象隐式转换为str错误python [重复]
【发布时间】:2013-09-27 06:35:02
【问题描述】:

我读过其他问题,但我想做的事情不同 我试图在 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 

任何帮助将不胜感激:)

【问题讨论】:

    标签: python-3.x int


    【解决方案1】:

    正如错误消息所说,您不能将 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' + str(2)
    'str2'
    

    或者使用str.format方法:

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

    【讨论】:

    • 您也可以在print 函数中使用逗号而不是+,因为它会自动将任何非字符串参数转换为str
    • 我想你帮了我 :) 我应该把它打印出来吗('答案是 {}'.format(answer))?
    • @soupuhman,是的,你可以像 Blckknght 评论的那样做 print('The answer is {}'.format(answer))print('The answer is', answer)
    猜你喜欢
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    相关资源
    最近更新 更多