0

I tried to replicate C++ style single line conditionals in Python like so:

I have a function defined : isPalidrome (mystr) - returns True if mystr is a palidrome,False otherwise. The function works.

Now I have a simple main function like so:

mystr =''
isitapalindromealready = lambda : if isPalindrome(mystr) ==True:    return "" else return 'not'
while mystr != 'quit':
    mystr = input("enter a string: ")
    print  ('{} is {} a palindrome'.format(mystr, isitapalindromealready())

But i get an Syntax error -

  File "scratch1.py", line 45
    isitapalindromealready = lambda : if isPalindrome(mystr) ==True:    return "" else return 'not'
                                       ^
SyntaxError: invalid syntax

I did check a similar thread that comes very close to replicating my logic above (it just does not call the lambda as a function anywhere).

Conditional statement in a one line lambda function in python?

However, none of the answers explain WHY it is a syntax error. If you ignore PEP 8, the syntax is valid unless you you cannot include else in the same line as if.

Any help, options, alternative considerations ? BTW: I wrote this simple program to check on this feature for reducing the logic size of much larger modules. I know very well that I can get away with checking if its a palindrome within the isPalindrome function. Thats not the point of my question.

Christian Dean
  • 19,561
  • 6
  • 42
  • 71
ssscld
  • 1
  • 2
  • 1
    @DYZ: Note that your previous edit invalidated the error message posted, so I rolled it back. – Christian Dean Sep 03 '17 at 00:29
  • Possible duplicate of [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – Arvind Sep 03 '17 at 00:33

1 Answers1

3

You can fit your conditionals on one line, definitely. This is how you do it in python.

isitapalindromealready = lambda x: "" if isPalindrome(x) else "not"

Sure, you can have lambdas work with global variables, but that is not how I would recommend doing it. A well written lambda should be a pure function, meaning you would pass the parameter to it. Additionally, the lambda needs no return as it is implied. Now, you must call your lambda as such:

isitapalindromealready(mystr)

isitapalindromealready = lambda x: "" if isPalindrome(x) else "not"
while mystr != 'quit':
    mystr = input("enter a string: ")
    print  ('{} is {} a palindrome'.format(mystr, isitapalindromealready(mystr))
cs95
  • 274,032
  • 76
  • 480
  • 537