Try to search your question here, if you can't find : Ask Any Question Now ?

Try-Except Clause Ignored in Linear List Insertion Algorithm Using Bisect Module (Python)

HomeCategory: stackoverflowTry-Except Clause Ignored in Linear List Insertion Algorithm Using Bisect Module (Python)
Avatarpushpa asked 6 days ago

I’m trying to insert an element into a linear list using input() with bisect() and insort() functions of the bisect module in Python 3.7. To accept only integer inputs, I tried adding a try-except clause (as suggested in an answer to: Making a variable integer input only == an integer in Python) as:

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)

I expected Python to catch the exception on entering a float, but it ignored the try-except clause and displayed this rather:

ind=bisect.bisect(m, item)
TypeError: '<' not supported between instances of 'str' and 'int'

What could be the possible issue?

Edit:

On changing except ValueError to except TypeError and entering ‘5.0’, I received ValueError:

item=int(item)
ValueError: invalid literal for int() with base 10: '5.0'
1 Answers
Best Answer
AvatarFernando answered 6 days ago
Your Answer

1 + 13 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com