1

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
3
  • What is the objective of the program? appending numbers to a list and finding largest and smallest number? Commented Mar 10, 2015 at 20:10
  • What makes you think the code in the try block will ever throw an exception? Commented Mar 10, 2015 at 20:19
  • If you want to make sure the user inputs an Integer, I would try int(num) on it. Commented Mar 10, 2015 at 20:35

1 Answer 1

0
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.