In python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to perform an if
in lambda
and if so how to do it?
thanks
In python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to perform an if
in lambda
and if so how to do it?
thanks
what you need exactly is
now call the function the way you need
why don't you just define a function?
there really is no justification to use lambda in this case.
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like
and
,not
,or
, etc) in their body.So, there's no way you could use a lambda for your example (because you can't use
raise
), but if you're willing to concede on that… You could use:Probably the worst python line I've written so far:
If x == 2 you print,
if x != 2 you raise.