trolle3000
trolle3000

Reputation: 1067

Trouble with simple Python Code

I'm learning Python, and I'm having trouble with this simple piece of code:

a = raw_input('Enter a number: ')

if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)

Thanks in advance

Upvotes: 4

Views: 588

Answers (6)

Justin Standard
Justin Standard

Reputation: 21545

Because you are using raw_input you are getting the value as a String, which is always considered greater than 0 (even if the String is '-10')

Instead, try using input('Enter a number: ') and python will do the type conversion for you.

The final code would look like this:

a = input('Enter a number: ')
if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

However, as a number of folks have pointed out, using input() may lead to an error because it actually interprets the python objects passed in.

A safer way to handle this can be to cast raw_input with the desired type, as in:

a = int( raw_input('Enter a number: '))

But beware, you will still need to do some error handling here to avoid trouble!

Upvotes: 7

nilamo
nilamo

Reputation: 1942

Expanding on my comment on the accepted answer, here's how I would do it.

value = None
getting_input = True

while getting_input:
    try:
        value = int(raw_input('Gimme a number: '))
        getting_input = False
    except ValueError:
        print "That's not a number... try again."

if value > 0:
    print 'Positive'
elif value < 0:
    print 'Negative'
else:
    print 'Null'

Upvotes: 7

Rob
Rob

Reputation: 504

raw input will return a string, not an integer. To convert it, try adding this line immediately after your raw_input statement:

a = int(a)

This will convert the string to an integer. You can crash it by giving it non-numeric data, though, so be careful.

Upvotes: 1

c_harm
c_harm

Reputation:

That's because a is a string as inputted. Use int() to convert it to an integer before doing numeric comparisons.

a = int(raw_input('Enter a number: '))
if a > 0:
    print 'Positive'
elif a == 0:
    print 'Null'
elif a < 0:
    print 'Negative'

Alternatively, input() will do type conversion for you.

a = input('Enter a number: ')

Upvotes: 7

Isaiah
Isaiah

Reputation: 4309

raw_input 

returns a string so you need to convert a which is a string to an integer first: a = int(a)

Upvotes: 5

Jon W
Jon W

Reputation: 15826

raw_input is stored as a string, not an integer.

Try using a = int(a) before performing comparisons.

Upvotes: 2

Related Questions