【问题标题】:need help. python integers and strings [duplicate]需要帮忙。 python整数和字符串[重复]
【发布时间】:2014-10-03 16:31:08
【问题描述】:

我正在编写的程序中的一行代码遇到了一些问题。当我运行该文件时,它会显示此消息:

Traceback (most recent call last):
  File "C:\Users\Main\Google Drive\computerprograming\mathoperationscalc.py", line 9, in <module>
    print('the sum of ' + x + ' and ' + y + ' is ')
TypeError: Can't convert 'int' object to str implicitly

代码如下:

print('please input 1st integer')
x = input()
x = int(x)
print('please input 2nd integer')
y = input()
y = int(y)

Sum = x + y
print('the sum of ' + x + ' and ' + y + ' is ')
print(Sum)

【问题讨论】:

  • (或其他 650 个 SO 问题中的任何一个,如果您费心用 Google 搜索错误消息。)

标签: python string integer


【解决方案1】:

您需要将int 转换为str 以便您可以连接。

x = int(input('please input 1st integer'))
y = int(input('please input 2nd integer'))

total = x + y
print('the sum of ' + str(x) + ' and ' + str(y) + ' is ')
print(Sum)

或使用format

'the sum of {} and {} is {}'.format(x,y,total)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2021-01-24
    • 2011-02-20
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多