TypeError: unsupported operand type(s) for -: 'str' and 'int'是什么意思?

2024-03-317764
AI 快速预览详细 收起
本文介绍了如何解决Python中常见的TypeError: unsupported operand type(s) for -: 'str' and 'int'问题。通过一个三角形数表解题器的例子,详细解析了错误原因,并提供了具体的解决方法。文章指出,由于输入的行和列是字符串类型,而后续的计算需要整数类型,因此需要使用int()函数进行类型转换。通过这一简单的调整,可以避免报错并使代码正常运行。

我写了一个解题器,代码如下:
import time



while True:
    print("欢迎使用三角形数表解题器")
    time.sleep(1)
    hang = input("请输入行")
    lie = input("请输入列")
    print((((hang + lie) - 1) * ((hang + lie) - 1)))
可运行了一半后,出现;


欢迎使用三角形数表解题器请输入行12请输入列3Traceback (most recent call last):  File "C:\Users\Administrator\Documents\mindplus-py\user\2024-03-31-11-58-03\11111.py", line 10, in <module>    print((((hang + lie) - 1) * ((hang + lie) - 1)))TypeError: unsupported operand type(s) for -: 'str' and 'int'




怎么办????????

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(2)
智慧牛牛
智慧牛牛
bug!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
TRIM
TRIM
[code]while True:
print("欢迎使用三角形数表解题器")
hang = input("请输入行")
lie = input("请输入列")
hang = int(hang)
lie = int(lie)
print((((hang + lie) - 1) * ((hang + lie) - 1)))[/code]
这样就可以了(输入默认是str类型,需要转换成int)
当然,如果你嫌这个不简洁,可以用这个
[code]while True:
print("欢迎使用三角形数表解题器")
hang = int(input("请输入行"))
lie = int(input("请输入列"))
print((hang + lie - 1)**2)
[/code]
- 没有更多了 -