Reputation: 25
small = None
larg = None
count = 0
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try:
num = float (inp)
except:
print "Invalid number"
if num < small:
small = num
print "Done"
print small
This code should make user add numbers until he/she types "done" and then find the smallest number (my idea is to compare num with small each time and it print last small value after done)
But when I run it, it keep showing None
as the smallest value.
Upvotes: 1
Views: 138
Reputation: 509
This is a fairly simple way of doing it. I haven't tried breaking it by typing gibberish into the prompt but I think it works ok.
numbers = []
def asking():
while True:
number = raw_input("Enter a number:")
if number == "stop":
break
try:
number = float(number)
numbers.append(number)
except:
print "Try again."
continue
return min(numbers)
print asking()
Upvotes: 0
Reputation: 485
I can suggest something like this
input_list = []
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try:
input_list.append(float(inp))
except:
print "Invalid number"
continue
smalest = min(input_list[-2:])
print smalest
input_list.append(input_list.pop(input_list.index(smalest)))
print "Done"
Upvotes: 0
Reputation: 949
You cannot initiate small
as None
value initially. Otherwise your statemtent
if num < small:
will evaluate to False
everytime. Because you are comparing None
value with a float value and None
is smaller than every number. Do something like this
if small is None or num < small:
small = num
Upvotes: 0
Reputation: 90889
In Python 2.x , None
is smaller than all numbers, hence since your starting number is None
, its always the smallest.
You can put a check that if small is None
to initialize with the input ( this should set your small
to the first inputted number).
Example -
small = None
larg = None
count = 0
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try:
num = float (inp)
except:
print "Invalid number"
if small is None or num < small:
small = num
print "Done"
print small
Upvotes: 2