The problem with simple Python code

I am learning Python and am having problems 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, except that it always prints "Positive", regardless of whether it is entering a positive or negative number or zero. I assume there is a simple solution, but I can not find it ,-)

Thank you in advance

+4
source share
6 answers

Since you use raw_input , you get a value like String, which is always considered to be greater than 0 (even if String has a value of "-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 people have pointed out, using input () can lead to an error, since it actually interprets the python objects passed to.

A safer way to handle this could be to reset the raw_input with the required type, as in:

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

But be careful, you still have to make some mistakes to avoid trouble!

+7
source

This is because a is the string entered. Use int() to convert it to an integer before doing numerical 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 the type conversion for you.

 a = input('Enter a number: ') 
+7
source

Expanding my comment on the accepted answer , here's how I 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 not a number... try again." if value > 0: print 'Positive' elif value < 0: print 'Negative' else: print 'Null' 
+7
source
 raw_input 

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

+5
source

raw_input stored as a string, not an integer.

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

+2
source

Raw input returns a string, not an integer. To convert it, try adding this line immediately after the raw_input statement:

a = int (a)

This will convert the string to an integer. You can compromise it by specifying it with non-numeric data, so be careful.

+1
source

All Articles