1

我想了解以下代码中 raw_input 的行为。我知道num会是字符串。无论我输入什么数字,它总是输入elif部分,即如果 num 为 5,则应进入if num<check:部分,或者如果 num 为 10,则应进入else部分。每一次它都会elif。我认为比较 STRING 和 INT 可能会抛出异常(我不这么认为),但以防万一,所以我已经包含了try except,但正如预期的那样,它没有抛出任何异常。但令我困惑的是,为什么elif即使给定的输入是 10,它也总是命中,至少在那种情况下,我期望输出相等

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

拜托,PYTHON 大师,解开这个谜团:)

4

3 回答 3

4

raw_input返回一个字符串。所以使用int(raw_input()).

对于 string 和 int 比较如何工作,请看这里

于 2013-07-14T09:20:25.307 回答
1

在这里查看答案

基本上你是在比较苹果和橘子。

>>> type(0) < type('10')
True
>>> 0 < '10'
True
>>> type(0) ; type('10')
<type 'int'>
<type 'str'>
于 2013-07-14T09:32:28.003 回答
0
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)
于 2015-06-30T11:51:39.687 回答