使用对分模块(Python)在线性列表插入算法中忽略Try-Except子句
我试图使用Python 3.7中使用对分模块(Python)在线性列表插入算法中忽略Try-Except子句,python,python-3.x,debugging,bisect,Python,Python 3.x,Debugging,Bisect,我试图使用Python 3.7中bisect模块的input()和insort()函数将元素插入线性列表中。为了只接受整数输入,我尝试添加一个try-except子句(如对:)作为: 我希望Python在输入浮点时捕获异常,但它忽略了try-except子句,并显示以下内容: ind=对分。对分(m,项目) TypeError:“问题在于,当您使用try/except子句捕获错误时,您不会做任何事情来确保项实际上是int 更合理的方法是循环,直到输入可以转换为int,例如: import bis
bisect
模块的input()
和insort()函数将元素插入线性列表中。为了只接受整数输入,我尝试添加一个try-except子句(如对:)作为:
我希望Python在输入浮点时捕获异常,但它忽略了try-except子句,并显示以下内容:
ind=对分。对分(m,项目)
TypeError:“问题在于,当您使用try
/except
子句捕获错误时,您不会做任何事情来确保项实际上是int
更合理的方法是循环,直到输入可以转换为int
,例如:
import bisect
m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The list is:", m)
# : loop until the input is actually valid
is_valid = False
while not is_valid:
item = input("Enter element to be inserted:")
try:
item = int(item)
except ValueError:
print("Invalid!")
else:
is_valid = True
ind = bisect.bisect(m, item)
bisect.insort(m, item)
print("Item inserted at index:", ind)
print("List after insertion:", m)
请注意,input()
总是获取一个str
,int('5.0')
也会抛出一个ValueError
,如果您也想处理这种情况,请使用两个try
s,例如:
import bisect
m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The list is:", m)
is_valid = False
while not is_valid:
item = input("Enter element to be inserted:")
try:
item = int(item)
except ValueError:
try:
item = int(round(float(item)))
# or just: item = float(item) -- depends on what you want
except ValueError:
print("Invalid!")
else:
is_valid = True
else:
is_valid = True
ind = bisect.bisect(m, item)
bisect.insort(m, item)
print("Item inserted at index:", ind)
print("List after insertion:", m)
异常发生后,程序继续运行。不符合逻辑。@Jean-Françoisfare我是编程新手;请原谅:)使用split()
检测非整数的方法效果更好。@Kartik基于split()
的方法可能不是很健壮,例如s='fgsdgfd'
可能会愚弄len(s.split('.')==1
检查。@norok2哦,是这样的。谢谢,tho。
import bisect
m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The list is:", m)
is_valid = False
while not is_valid:
item = input("Enter element to be inserted:")
try:
item = int(item)
except ValueError:
try:
item = int(round(float(item)))
# or just: item = float(item) -- depends on what you want
except ValueError:
print("Invalid!")
else:
is_valid = True
else:
is_valid = True
ind = bisect.bisect(m, item)
bisect.insort(m, item)
print("Item inserted at index:", ind)
print("List after insertion:", m)