Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm attempting to make a function where when I call the function it prompts the client/user to enter a number and returns whether it is even or odd. I'm attempting to make it so my code prints an error to the console when nothing is entered or when a string is entered, I have come to the heart of the matter whereby on the off chance that I enter a number it returns number, "is an even number" on the off chance that it is even and number, "is definitely not an even number" in the event that it isn't even. Here is my code beneath I'm utilizing python 2.7.3

def is_even():

    x = int(raw_input("Enter number"))

    if x % 2 == 0:

        return x, "is an even number"

    else:

        return x, "is not an even number"

print is_even()

1 Answer

0 votes
by (26.4k points)

You can use try-except block:

def is_even():

    try:

        x = int(raw_input("Enter an integer: "))  # 'number' != 'integer'

        if x % 2 == 0:

            return x, "is an even number"

        else:

            return x, "is not an even number"

    except ValueError:

        return "Error: You didn't enter an integer!"

Want to become a expert in Python? Join the python course fast!

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
4 answers

Browse Categories

...