Cyr1lfiggus
Cyr1lfiggus

Reputation: 89

python incorrectly values < and >

The following is my code that calculates <, > incorrectly. About 3X into giving raw_input it will do things like value 12 < 4. I have added several float commands to try to keep it from having problems with string and int. I'm very new to coding.

largest = None
smallest = None
while True:
    num = raw_input("Enter a number: ")
    if num == "done" : break
    try:
        float(num)
    except ValueError:
        print "Invalid input" 
        break
    float(num)
    if largest is None:
        largest = num
        float(largest)
    if smallest is None:
        smallest = num
        float(largest)
    if num > largest:
        largest = num
        float(largest)
    if num < smallest:
        smallest = num
        float(smallest)
    print num

print "Maximum", largest
print "Minimum", smallest

Upvotes: 1

Views: 76

Answers (4)

Suever
Suever

Reputation: 65430

In your current code, after casting num as a float, you never actually assign it to anything.

float(num)

Instead you will want to re-assign num after the conversion

num = float(num)

If you don't do this (as in your current code), when you're performing the comparisons, you're doing a string comparison rather than a numeric comparison.

"12" < "4"   # True

Upvotes: 1

wandadars
wandadars

Reputation: 1183

You don't change the value in num in your code. Typing "float(num)" doesn't really do anything because it's just temporarily casting that variable as a floating point number. To actually change the value I suggest the following edits.

largest = None
smallest = None
while True:
    num = raw_input("Enter a number: ")
    if num == "done" : break
    try:
        float(num)
    except ValueError:
        print "Invalid input" 
        break
    num = float(num)
    if largest is None:
        largest = num
    if smallest is None:
        smallest = num
    if num > largest:
        largest = num
    if num < smallest:
        smallest = num
    print num

print "Maximum", largest
print "Minimum", smallest

Upvotes: 0

Mureinik
Mureinik

Reputation: 311228

float does not change the variable in-place - it returns a cast value, which you are ignoring by not saving it anywhere. Just assign it, and you should be OK:

try:
    num = float(num)
except ValueError:
    print "Invalid input" 
    break

if largest is None:
    largest = num
if smallest is None:
    smallest = num
if num > largest:
    largest = num
if num < smallest:
    smallest = num
print num

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

float(num) computes the floating-point value of num, but doesn't do anything with it; in particular, it doesn't change the value of num. You'll need an assignment to do that.

Upvotes: 1

Related Questions