1
votes

I am struggling with my code - can sb help ? why it does not print "Invalid input" when i run it in Python and enter something else than the integer ?

Basically the program should run in endless loop until we enter "done". so even after except it should still prompt for entering a number.

largest = None
smallest = None
while True:
    num = raw_input("Enter a number: ")
    try:
       if num == "done" :
            print "Maximum is", largest
            print "Minimum is", smallest
            exit
       if largest is None:
           largest = num
       elif largest < num:
           largest = num
       if smallest is None:
           smallest = num
       elif smallest > num:
           smallest = num 
    except int(num) == -1:
        print "Invalid input"
        continue
1
What is the objective of the program? appending numbers to a list and finding largest and smallest number? - letsc
What makes you think the code in the try block will ever throw an exception? - Paul Rooney
If you want to make sure the user inputs an Integer, I would try int(num) on it. - MikeVaughan

1 Answers

0
votes
largest = None
smallest = None
try:
    num = raw_input("Enter a number: ")
    x = int(num, base = 10)  
except:
    print "Invalid input"

while num != "done":    
    try:
    num = raw_input("Enter a number: ")
    x = int(num, base = 10)  
    except:
        print "Invalid input"
        continue

    if largest is None:
        largest = num
    elif largest < num:
        largest = num
    if smallest is None:
        smallest = num
    elif smallest > num:
        smallest = num  
print "Maximum is", largest
print "Minimum is", smallest
exit