0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ajay
  • 53
  • 8
  • Rather than tell us what your IDE thinks about the code, it's better to see what Python thinks of it when it tries executing the code. This should give you a `SyntaxError` which can be [copied and pasted as properly formatted text](https://meta.stackoverflow.com/questions/359146), and properly shows the problem - [please do not upload images of errors when asking a question](//meta.stackoverflow.com/q/285551), and please show actual errors when possible. – Karl Knechtel Aug 27 '22 at 04:41
  • As for the problem, it means exactly what you are told: the part after `else` has to be an *expression*, and using `return` makes a *statement*. It is the same problem as if you had written `return 1 + return 2`, instead of `return 1 + 2`. What is written after `else` is **not** "what to do when the condition isn't met", it's "*what the value should be* when the condition isn't met". I closed this as a duplicate of the general reference question for this construction, which Python calls a *conditional expression*. – Karl Knechtel Aug 27 '22 at 04:41

1 Answers1

0

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
Barmar
  • 741,623
  • 53
  • 500
  • 612