Hyeon Ju Yu Hyeon Ju Yu - 11 days ago 6
Python Question

checking if the input is int >=0 using if statement

IDnum = input("\nprompt: ")

if int(IDnum) >= 0 :
if int(IDnum) in T.keys() :
print("ID number(s) that {} will contact is(are) {}.".format(int(IDnum),T[int(IDnum)]))
else :
print("Entered ID number {} does not exist.".format(int(IDnum)))
else:
break


It's actually a while loop, receiving ID numbers and checking whether the numbers are in the file.

I'd like to make it discern whether the input is an integer >= 0 and if it's anything else, (eg. space,enter,characters,float,etc) break the loop.

How can I do this using if statements?

I have tried
if IDnum == '' or IDnum == ' ' or int(IDnum) < 0 :
but as you know, it cannot cover all the other cases.

Answer
T = {1: 1, 2: 2}
while True:
    IDnum = input("\nprompt: ")
    try:
        num = int(IDnum)
    except ValueError: # parsing a non-integer will result in exception
        print("{} is not a valid integer.".format(IDnum))
        break
    if num >= 0 :
        if num in T :
            print("ID number(s) that {} will contact is(are) {}.".format(num,T[num]))
        else :
            print("Entered ID number {} does not exist.".format(num))
    else:
        break