Search code examples
pythonpython-3.xreturnsyntax-error

Syntax Error in Function Return Statement


I'm a python beginner and I'm trying to write this function:

def order(sentence):
    return '' if sentence==''

This function basically returns an empty string if the argument (which is called sentence) is an empty string. I know I can simply do this instead:

def order(sentence):
    if sentence=='':
      return ''

Nevertheless, I am curious why the first example doesn't work. I can't really see what I wrote wrong. I am using python 3.8 by the way. Thanks for the help in advance.


Solution

  • When doing a conditional expression, you need an else as well. It will not work otherwise.

    def order(sentence):
        return '' if sentence=='' else None # or anything else
    

    Resources: