Search code examples
pythonsyntaxreturnconditional-operator

Using if/else on the same line with return statement


I'm trying to condense my code by putting my conditional statement onto one line.

def get_middle(s):
    if len(s)%2 == 1: return(s[int(len(s)/2)]) 
    else: return(s[int(len(s)/2)-1] + s[int(len(s)/2)])

This works just fine. I tried to do it this way:

return(s[int(len(s)/2)]) if len(s)%2 == 1 else return(s[int(len(s)/2)-1] + s[int(len(s)/2)])

but I'm met with a syntax error at the end of that line.

Error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from solution import *
  File "/home/codewarrior/solution.py", line 5
    return(s[int(len(s)/2)]) if (len(s)%2 == 1) else (return(s[int(len(s)/2)-1] + s[int(len(s)/2)]))
                                                           ^
SyntaxError: invalid syntax

Also: This is mainly just because I'm curious. I understand in a real-world application this code would be too hard to interpret.


Solution

  • You cannot have the return keyword called again, because you already have the return at the start of the if and the else.

    Do this instead:

    return(s[int(len(s)/2)]) if len(s)%2 == 1 else (s[int(len(s)/2)-1] + s[int(len(s)/2)])
    

    Also,

    that line is super unclear, maybe you should have sticked to the regular if and else statement, as you probably won't undertant a thing after coming one month later.