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
<
If you still want to print you can import future module
from __future__ import print_function
f = lambda x: print(x) if x%2 == 0 else False
Hope this will help a little
you can resolve this problem in the following way
f = lambda x: x==2
if f(3):
print("do logic")
else:
print("another logic")
Try it:
is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))
Out:
True
False
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
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:
f = lambda x: x == 2 and x or None
I think this is what you were looking for
>>> f = lambda x : print(x) if x==2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>>