为什么这个简单的代码不适用于Python?

时间:2013-02-16 17:42:10

标签: python python-2.7

x = raw_input("Write a number")
if x.isalpha():
    print "Invalid!"
elif x%2==0:
    print "The number you have written is EVEN"
elif x%2!=0:
    print "The number you have written is ODD"
else:
    print "Invalid!"

应该检查数字是奇数还是偶数并将其打印出来。我的if语句检查raw_input是否是字母表,因为这不起作用。我的elif语句检查奇数或偶数。

2 个答案:

答案 0 :(得分:5)

raw_input的返回值始终为字符串。如果要在其上使用%运算符,则需要将其转换为整数:

x = raw_input("Write a number")
if x.isalpha():
    print "Invalid!"
x = int(x)

而不是x.isalpha(),您可以改为使用exception handling

try:
    x = int(raw_input("Write a number"))
except ValueError:
    print 'Invalid!'
else:
    if x % 2 == 0:
        print "The number you have written is EVEN"
    else:
        print "The number you have written is ODD"

因为如果输入不是有效整数,int()将引发ValueError

答案 1 :(得分:1)

raw_input的返回值是一个字符串,但您需要一个数字来进行奇偶校验测试。 您可以检查它是否是字符串,如果不是,则将其转换为int。 例如:

xs = raw_input("Write a number")
if xs.isalpha():
    print "Invalid!"
else:
    xn = int(xs)
    if xn % 2 == 0:
        print "The number you have written is EVEN"
    elif xn % 2 != 0:
        print "The number you have written is ODD"
    else:
        print "The universe is about to end."