我正在尝试使用Python 3.7 中模块的input()
withbisect()
和insort()
函数将元素插入到线性列表中。bisect
为了只接受整数输入,我尝试添加一个 try-except 子句(如答案中所建议的:Making a variable integer input only == an integer in Python):
import bisect
m=[0,1,2,3,4,5,6,7,8,9]
print("The list is:", m)
item=input("Enter element to be inserted:")
try:
item=int(item)
except ValueError:
print("Invalid!")
ind=bisect.bisect(m, item)
bisect.insort(m, item)
print("Item inserted at index:", ind)
print("List after insertion:", m)
我希望 Python 在输入浮点数时捕获异常,但它忽略了 try-except 子句并显示了这个:
ind=bisect.bisect(m, item) TypeError: '<' 在 'str' 和 'int' 的实例之间不支持
可能的问题是什么?
编辑:
在更改except ValueError
并except TypeError
输入“5.0”时,我收到了 ValueError:
item=int(item) ValueError: int() 以 10 为底的无效文字:'5.0'