0
votes

I'm new to Python (or any coding really) and need to return max and min values from array entered by user. I can get it to return the max no problem, but min gives me <unknown> message back. Can anybody help me fix the code for my min return? Thanks.

Here is my code:

maximum = None
minimum = None

while True:
    #enter the input
    inp = raw_input("Enter a number:")

    #handle the edge cases
    if inp == "done" : 
        break
    if len(inp) < 1 : 
    break

    #only accept good input
    try: 
        num = int(inp)
        #print num
    except:
        print "Invalid input"
        continue

    #do the work
    if num > maximum :
        max = num
    if num < minimum :
        min = num
    else:
        num

print "Maximum is", max
print "Minimum is", min
3
No number is less than None, so the line min = num is never run.Jared Goguen
but min gives me message back <- Is it a private message or can we see the error?timgeb
@timgeb It's because min is a built-in, so it prints that.Jared Goguen
Thank you. It makes perfect sense that nothing is less than None.3LP

3 Answers

1
votes

Try to initialise minimum and maximum to a number and not None.

Compare as INT values , here you are doing as strings

1
votes

You can take two approaches, here. First, you can explicitly check for None in your code. The second, as mentioned by @minatverma, is to initialize your min/max values to some "cannot be reached" values.

Option 1:

Replace this code ...

#do the work
if num > maximum :
    max = num
if num < minimum :
    min = num
else:
    num

With this code:

#do the work
if minimum is None:
    # First time, only
    minimum = num
    maximum = num
elif num > maximum:
    maximum = num
elif num < minimum:
    minimum = num

Option 2:

You will need to add the following line at the top of your code:

import math

Then, replace this code:

maximum = None
minimum = None

With this:

maximum = -math.inf
minimum = math.inf

The rest of your code can stay the same.

-1
votes

Try to put all entered numbers into a INT list (array) and then use built-in min() and max() functions...

from __future__ import print_function

nums = []

while True:
    #enter the input
    inp = input("Enter a number:")

    #handle the edge cases
    if inp == "done" or not len(inp): 
        break

    #only accept good input
    try: 
        nums.append(int(inp))
    except ValueError:
        print("Invalid input")
        continue

print("Maximum is", max(nums))
print("Minimum is", min(nums))