简体   繁体   中英

Creating a function that negates return value of another function

I am new to Python 3 and currently practicing with functions. I wanted to first write a function that returns True or False depending on whether its parameter (int) is even.

def isEven(number):
    if number % 2 == 0:
        return True
    elif number % 2 != 0:
        return False

This worked as I could print the return value with the print() function. However, I had problems when I wanted to write a second function, which is the isOdd() function. I wanted it to negate the whatever return value of isEven() . I tried:

def isOdd (number):
    return not isEven(number)

Is there a more efficient way, say, by creating a conditional statement in isOdd() ?

If we talk about only this example then you can use if. But if isEven is bigger in realtime world, you should call it in isOdd

I'd minimize isEven with like this

def isEven(number):
    return number % 2 == 0

Then you might not need isOdd() , since isEven() will return false then.

You can also eliminate the if-elif statement:

def isEven(number):
    return number%2 == 0

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