Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with simple Python Code

Tags:

python

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

like image 646
trolle3000 Avatar asked Nov 28 '22 12:11

trolle3000


1 Answers

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!

like image 66
Justin Standard Avatar answered Dec 16 '22 04:12

Justin Standard