【python】算术运算报错can't multiply sequence by non-int of type 'float'

xiaoxiao2021-02-28  98

举例:

num1=input('input the first num: ')

num2=input('input the second num: ') num3=num1*num2 print(num3)

执行后,结果:input the first num:这时自己在键盘输入整数,敲回车

                          input the second num:再次在键盘输入整数,敲回车

开始报错:can't multiply sequence by non-int of type 'float'

原因:input()函数输入的是字符串格式,所以自己在键盘输入的整数其实并不是正整数,而是字符串形式。所以在执行语句num3=num*num会报错。因为num1和num2都是字符串形式,不可以相乘。

解决思路:把num1和num2强制转换成整数

具体解决方法

1.代码第三行改为:  num3=int(num1)*int(num2)

2.第一二行改为:num1=int(input('input the first num: '))

                               num2=int(input('input the first num: '))

推荐第一种解决方法

转载请注明原文地址: https://www.6miu.com/read-59770.html

最新回复(0)