0

我正在尝试使用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 ValueErrorexcept TypeError输入“5.0”时,我收到了 ValueError:

item=int(item) ValueError: int() 以 10 为底的无效文字:'5.0'

4

1 回答 1

1

问题是,当您使用try/except子句捕获错误时,您没有做任何事情来确保它item实际上是一个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()总是得到 astrint('5.0')抛出 a ValueError,如果你也想处理这种情况,请使用两个trys,例如:

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)
于 2019-10-08T16:46:25.893 回答