Behaviour of raw_input()

2019-01-07 01:33发布

问题:

I wanted to understand the behaviour of raw_input in the below code. I know num will be string. Irrespective of whatever number i enter it always enter the elif part i.e. if num is 5, which should go to if num<check: part or if num is 10 which should go to else part. Every single time it is going to elif. I thought comparing STRING and INT might throw exception( I dont think so) but just in case, so I had included try except but as expected it did not throw any exception. But what puzzles me is why it is ALWAYS hitting elif even when the input given was 10, atleast in that case i was expecting output Equal

num = raw_input('enter a number')
check = 10
try:
    if num<check:
        print 'number entered %s is less'%num

    elif num>check:
        print 'number entered %s is greater'%num

    else:
        print 'Equal!!!'
    print 'END'
except Exception,e:
    print Exception,e

Please, PYTHON gurus, solve the Mystery :)

回答1:

raw_input returns a string. So use int(raw_input()).

And for how string and int comparsions work, look here.



回答2:

See the answer here.

Basically you're comparing apples and oranges.

>>> type(0) < type('10')
True
>>> 0 < '10'
True
>>> type(0) ; type('10')
<type 'int'>
<type 'str'>


回答3:

Python 2.7:    
num = int(raw_input('enter a number:'))
Variable "num" will be of type str if raw_input is used.
type(num)>>str
or 
num = input("Enter a Number:")# only accept int values
type(num)>>int

Python 3.4 : 
num = input("Enter a Number:") will work ...
type(num)>>str
convert the variable "num" to int type(conversion can be done at time of  getting the user "input") :
num1 = int(num)