Reputation: 51
I wonder if you could help me with the code below:
min = None
max = None
while True:
input = raw_input("Please enter number: ")
if input == "done":
break
else:
try:
input = float(input)
except:
continue
if max < input:
max = input
elif min > input:
min = input
print min
print max
It looks right to me, but the elif statement which gives a value to min always prints None
. Could you please explain why?
Upvotes: 0
Views: 54
Reputation: 3088
Your min > input
is always going to be false if min
is None
, hence why it never gets set.
Also you don't want the elif
. The first number is both the min and the max.
Fixed:
min = None
max = None
while True:
input = raw_input("Please enter number: ")
if input == "done":
break
else:
try:
input = float(input)
except:
continue
if max is None or max < input:
max = input
if min is None or min > input:
min = input
print min
print max
Good luck!
Upvotes: 0
Reputation: 1121306
None > number
is never true, because Python 2 sorts None
before any other type. Don't compare numbers with None
.
Either test for None
explicitly, or replace None
with an infinity value.
Testing for None
:
if max is None or max < input:
max = input
elif min is None or min > input:
min = input
Setting the values to positive or negative infinity:
min = float('inf')
max = float('-inf')
By setting min
to positive infinity, any other number is guaranteed to be smaller; the same applies to max
negative infinity.
Upvotes: 4