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.

2 answers

  • answered 2021-05-03 18:01 m.i.cosacak

    you can try as following:

    def order(sentence):
        return '' if sentence=='' else "x" # or something else
    

  • answered 2021-05-03 18:01 12944qwerty

    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: