Search code examples
python-3.xmaxuser-inputminimum

Finding minimum and maximums in python without lists


So I need to write a code to find the minimum and maximum number from a set of integers inputted by a user but I am not allowed to use lists. This is what my code looks like so far.

sum = 0
counter = 0
done = False 
while not done:
    integer_input = int(input("Please enter a number.")) 
    if counter < 9:
        counter += 1
        sum = sum+integer_input
    else:
        done = True 
print("The average of your numbers is:", sum/10,"The minimum of your  numbers is:" "The maximum of your numbers is:")

Is there a for loop I could use or something from the math module possibly?


Solution

  • To fix your code: You can set a min_ and a max_, and then compare the integer input each time. if your input is less then min_, overwrite that variable. If it is greater than max_, overwrite that variable:

    sum_ = 0
    counter = 0
    done = False
    while not done:
        integer_input = int(input("Please enter a number."))
        if counter == 0:
            min_ = integer_input
            max_ = integer_input
        if counter < 9:
            if integer_input < min_:
                min_ = integer_input
            if integer_input  > max_:
                max_ = integer_input
            counter += 1
            sum_ = sum_+integer_input
        else:
            done = True 
    
    
    print("The average of your numbers is:{}, The minimum of your numbers is: {}, The maximum of your numbers is: {}".format(sum_/10, min_, max_))
    

    Example input:

    Please enter a number.1
    Please enter a number.2
    Please enter a number.3
    Please enter a number.4
    Please enter a number.5
    Please enter a number.6
    Please enter a number.5
    Please enter a number.4
    Please enter a number.3
    Please enter a number.2
    >>> print("The average of your numbers is:{}, The minimum of your numbers is: {}, The maximum of your numbers is: {}".format(sum_/10, min_, max_))
    The average of your numbers is:3.3, The minimum of your numbers is: 1, The maximum of your numbers is: 6