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 snippet should help you:
x = lambda age: 'Older' if age > 30 else 'Younger'
print(x(40))
You can also use Logical Operators to have something like a Conditional
func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse
You can see more about Logical Operators here
An easy way to perform an if in lambda is by using list comprehension.
You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:
f = lambda x: print(x) if x==2 else print("exception")
Another example:
return 1 if M otherwise 0
f = lambda x: 1 if x=="M" else 0
The syntax you're looking for:
lambda x: True if x % 2 == 0 else False
But you can't use print
or raise
in a lambda.