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.