python如何处理type(s) for +: 'int' and 'str'

时间:2024-10-12 00:37:28

1、首先介绍下今天用到的python版本,现在在用的版本有两个:一个是python2.7.15,一个是python3.6.5。今天这里用到的是3的版本。

python如何处理type(s) for +: 'int' and 'str'

2、看一下这个例子,编辑一个可以计算从1到100的累加罗列的简单程序。按照图标程序进行运行,就会报错。

python如何处理type(s) for +: 'int' and 'str'

3、程序开始会正常运行,当输入数字1,系统就会提示错。提示为“TypeError: unsupported operand type(s) for +: 'int' and 'str'”,这个错误就是说输入的字符类型没有被系统判定为整数类型。

python如何处理type(s) for +: 'int' and 'str'

4、遇到这种情况,我们只需将输入的类型进行整合成整数类型就可以了。在input前加上“int”。

python如何处理type(s) for +: 'int' and 'str'

5、重新运行一下,看到这次就没有再次报错,程序正常运行并计算出了我们想要的结果。

python如何处理type(s) for +: 'int' and 'str'

6、最后注意一下,这个情况在python2.7.15中就不会出现这个情况。这可能就是不同版本之间存在的差异吧。

python如何处理type(s) for +: 'int' and 'str'
© 手抄报圈