Reputation: 8959
I must be doing something stupid but I just don't see it. I could not get the following simple code to work.
>>> def a_bigger_than_b(a,b):
... 'Yes' if a > b
File "<stdin>", line 2
'Yes' if a > b
^
SyntaxError: invalid syntax
Upvotes: 0
Views: 163
Reputation: 8692
def a_bigger_than_b(a,b):
... return 'Yes' if a > b else 'No!'
Actually your using it as Ternary Operator
in such case you need else
i think you must give else this can be well understood by
first
c='Yes' if a > b
what will be the value for a if a is smaller than b this case is ambiguous so else is must
correct syntax
c='Yes' if a > b else 'No!'
A detailed explanation was given by here
*On 9/29/2005, Guido decided to add conditional expressions in the
form of "X if C else Y".
The motivating use case was the prevalance of error-prone attempts
to achieve the same effect using "and" and "or".
Previous community efforts to add a conditional expression were
stymied by a lack of consensus on the best syntax. That issue was
resolved by simply deferring to a BDFL best judgment call.*
Upvotes: 4
Reputation: 91017
Your syntax resembles me a bit of Perl.
I am not sure what exactly you want
def a_bigger_than_b(a,b):
'Yes' if a > b
to do; there are several possimble interpretations.
Amongst the ones already mentioned, you could as well want
def a_bigger_than_b(a, b):
if a > b: return 'Yes'
which does nothing in the <=
case and eventually reaches the end of the function, where (implicitly) None
is returned.
This is the one-liner syntax for Python, quite equvalent to the do_whatever if foo
syntax in Perl.
Be aware that a function must always return a value; if you don't explicitly, None
is returned implicitly.
Upvotes: 2
Reputation: 712
You may change if statement in simpler one:
def a_bigger_than_b(a, b):
return a > b and 'Yes'
Upvotes: 1