Diesan Romero
Diesan Romero

Reputation: 1658

Trying to get if a negative number is even or odd in python

I have a code in python to know if a number is even or odd. But when I pass a negative number I receive another value. For example:

def even_or_odd(number):

    if (number % 2) == 0:
        return "Even"
    elif number < 0:
        return "Even"
    else:
        return "Odd"

if I select number -1 I expect Odd but I receive Even.

Upvotes: 1

Views: 1578

Answers (1)

Holden
Holden

Reputation: 642

That's because it is hitting the less than 0 if statement first.

What you are checking for here is a number is even and negative, not if it is even or odd. The traditional way you check for even or odd still applies to negative numbers:

if number % 2 == 0:
    return "Even"
else:
    return "Odd"

This still works with negative numbers.

Upvotes: 3

Related Questions