Search code examples
pythonbreakcontinue

Try except bug check


I'm doing a certain online course and I've completed the assignment with this code, but I can still induce a bug with certain inputs, and I can't understand why. I've asked the course mentors (using pseudo code) and they say there's a problem with my try/except statement.

The program should prompt a user for a number, over and over again, returning an error if something non-numeric is entered, with the exception of the string 'done,' in which case it will return the maximum and minimum of all the numbers entered.

Here's the program:

largest = None
smallest = None

while True:

    num = input("Enter a number: ")


    if num == 'done': break

    try:  
        float(num)

    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)

If you enter the following values as input 1 2 3 pk 27 -37 done, the output is Max: 3, Min -37.

It's driving me crazy. I have do idea why this is happening.


Solution

  • You are casting the input to a float, but not retaining that for later checks.

    So later on after the except block, Python is doing string comparisons and is comparing the string "3" to the string "27" and since '3' is 'larger' than '2' it considers "3" larger than "27", much like "b" is larger than "aaabbbbzzz".

    To fix it change this:

    float(num)
    

    to this:

    num = float(num)