简体   繁体   中英

Why isn't this simple code working, for Python?

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!"

It is supposed to check if the number is odd or even and print it out. My if statement checks if the raw_input was an alphabet because that won't work. And my elif statements check for odd or even.

The return value of raw_input is always a string. You'll need to convert it to an integer if you want to use the % operator on it:

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

Instead of x.isalpha() you can use exception handling instead:

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"

because int() will raise ValueError if the input is not a valid integer.

The return value of raw_input is a string, but you need a number to do the parity test. You can check whether it's an alpha string, and if not, convert it to an int. For example:

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM