Search code examples
pythondata-structuresstack

Error return a function using if-else shorthand in python


I'm trying to use this if-else shorthand inside a function:

def isFull(): # checks wheteher stack is full
    return True if top == (size - 1) else return False

But my IDE highlights the return saying "Expected expression".

What is wrong with the code, and how do I fix it?


Solution

  • You don't repeat return inside the conditional expression. The conditional expression contains expressions, return is a statement.

    def isFull():
        return True if top == (size - 1) else False
    

    But there's really no reason for the conditional expression at all, just return the value of the condition, since it's True or False.

    def isFull():
        return top == size - 1