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

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It looks like OP has just started learning Python. He shouldn't have learned about try, execpt, finally and others at this stage. I am saying this because I am pretty new too... And using raw_input is one of the building blocks in most of the books/tutorials... :)
@Aditya: that's why I am suggesting exception handling, and linked that to the tutorial section on that technique. :-)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.