Search code examples
pythonloopspython-3.3python-idlesentinel

Python: Loop Sentinel Value


I'm supposed to write a program with a loop that lets the user enter a series of integers, followed by -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.

This is what I have so far:

def main():
    user_input = 1
    while user_input != -99:
        user_input = int(input("Enter your number or -99 to end."))
        bigger = largest(user_input)
        tinier = smallest(user_input)
    print('The largest number is ', bigger, "and the smallest is ", tinier, ".")     

def largest(number):
    largest = 0
    if number > largest:
        largest = number
        return largest 

def smallest(number):
    smallest = 10000
    if number < smallest:
        smallest = number
        return smallest


main()

For some reason the sentinel value (-99) is entering the loop, I have no clue how, and becoming the smallest value. On top of that, the biggest value isn't ever the right one. Help much appreciated!


Solution

  • The quickest change to make to your code to fix this would be

    def main():
        user_input = 1
        while user_input != -99:
            user_input = int(input("Enter your number or -99 to end."))
            if use_input == -99:
                break
            bigger = largest(user_input)
            tinier = smallest(user_input)
        print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
    

    The problem is, if the user enters -99, you complete the rest of the lines for that iteration of the loop. It will not terminate the while loop until the next time around, but it has already performed largest and smallest at that point so it is already overwritten.