1
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 语句检查奇数或偶数。

4

2 回答 2

5

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

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

x.isalpha()你可以使用异常处理来代替:

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

于 2013-02-16T17:44:07.450 回答
1

的返回值raw_input是一个字符串,但是你需要一个数字来做奇偶校验。您可以检查它是否为 alpha 字符串,如果不是,则将其转换为 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."
于 2013-02-16T17:53:37.173 回答