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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With