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.

1
  • 1
    Maybe it's better to let user type all numbers and then show smallest? Commented Jul 10, 2015 at 6:00

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

What if the user enters all numbers greater than 9999999?
yea thanks that give some advantage of making code smaller :D
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"

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.