pythondebuggingvariable-assignmentnew-operatorcoursera-api

Getting minimum and maximum from inputs


Coursera python assignment

I do not understand what is wrong with this code. It works well for the largest, but not the smallest. And both line of codes are the same! I am new here and new to programming as well, pardon my inexperence . Please note that I need to solve this problem with these methodes as it was insructed in the chapter in the course.

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if (num=="done"): 
        break
    else:
        try:
            num=int(num)
        except:
            print("Invalid input") 
            continue
    if(num < smallest):
        smallest = num
    elif(num > largest):
        largest = num
print("Maximum is", largest)
print("Minimum is", smallest)

Solution

  • You shouldn't set smallest and largest to None, because you can't compare this with a number.

    Instead, you should set them both to the first input. Then you can compare additional numbers to them. And if only one number is entered, it will be the mamimum and minimum.

    I've moved reading the number into a function, to avoid repeating the validation loop in both places.

    def get_number():
        while True:
            num = input("Enter a number: ")
            if num == "done":
                return num
            try:
                num = int(num)
                return num
            except:
                print("Invalid input")
    
    smallest = get_number()
    largest = smallest
    if smallest == "done":
        print("At least one number must be entered")
    else:
        while True:
            num = get_number()
            if num == "done":
                break
            if num < smallest:
                smallest = num
            elif num > largest:
                largest = num
        print("Maximum = ", largest)
        print("Minimum = ", smallest)
    

    Test results:

    $ python testminmax.py
    Enter a number: 7
    Enter a number: 2
    Enter a number: bob
    Invalid input
    Enter a number: 10
    Enter a number: 4
    Enter a number: done
    Maximum =  10
    Minimum =  2