0

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'

Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
Kartik
  • 33
  • 1
  • 7

1 Answers1

1

The issue is that while you catch the error with the try/except clause, you do not do anything to make sure that item is actually a int.

A more reasonable approach is to loop until the input can be converted to int, for example:

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)

Note that input() always gets a str and int('5.0') also throws a ValueError, if you want to handle that case as well, use two trys, e.g.:

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)
norok2
  • 25,683
  • 4
  • 73
  • 99