Maximum and minimum of integers in python using none type

Question:

Am using Python 2.7 .I tried initializing smallest and largest to none and then split the if’s into 2 conditions.
The problem is the smallest is always none. I don’t get the minimum of the numbers entered. What is going on here?

largest=None
small=None


while True:
 num = raw_input("Enter a number: ")
 if num == "done" : break
 else:
  n1=int(num)

  print largest
  n1= int(num)
  print small
 if n1 <small:
  small=n1

 if n1> largest:
  largest=n1


print "Maximum", largest
print "Min", small
Asked By: user42836

||

Answers:

In Python 2.7 , the issue is that if you compare an int with None, None would always be smaller than any int. Example to show this –

>>> -100000000000 < None
False

What you would need to do is to put a condition like –

if small is None:
    small = n1
elif small > n1:
    small = n1
Answered By: Anand S Kumar

Use sys.maxint instead of None:

import sys

largest=-sys.maxint-1
smallest=sys.maxint

Since you want the first number to to be largest and smallest, make largest initially the smallest int possible — in the case -sys.maxint-1 Converse is true with smallest — make that sys.maxint

Btw, you cannot compare and int and None on Python 3.

Answered By: dawg
def maxmin():
    largest = None
    smallest = None
    while True:
        numar = input("Enter a number: ")
        if numar == "":
            break

        numar = int(numar)

        if largest is None:
            largest = numar
            if smallest is None:
                smallest = numar
        else:
            if numar < smallest:
                smallest = numar
            if numar > largest:
                largest = numar
    print("Maximum is", largest, 'nMinimum is', smallest)

maxmin()
Answered By: aurel_c12

Semantically you dont need the line "if smallest is None:", as the first element read is by defintion the smallest and largest so far. But as someone has already said I think posting complete solutions to Coursera assignments goes against their honor code!

Answered By: Tony C
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.