【python】算术运算报错can’t multiply sequence by non-int of type ‘float’
1、can’t multiply sequence by non-int of type 'float’
举例:
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: '))
推荐第一种解决方法
2、TypeError: can’t multiply sequence by non-int of type 'str’
print(‘x*y=’,input()*input())
1024
768
Traceback (most recent call last):
File “”, line 1, in
TypeError: can’t multiply sequence by non-int of type ‘str’
进行强制类型转换后运行正常
print(‘x*y=’,int(input())int(input()))
1024
768
xy= 786432