1
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.

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
Solo
  • 25
  • 6

4 Answers4

2

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
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

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
Naman Sogani
  • 943
  • 1
  • 8
  • 28
0

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"
0

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()
Byte
  • 509
  • 6
  • 15