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
note you can use several else...if statements in your lambda definition:
You can easily raise an exception in a lambda, if that's what you really want to do.
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don't think this is inherently evil, though--I consider the "y if x else z" syntax itself worse--just make sure you're not trying to stuff too much into a lambda body.
The syntax you're looking for:
But you can't use
print
orraise
in a lambda.If you still want to print you can import future module
You can also use Logical Operators to have something like a Conditional
You can see more about Logical Operators here
This snippet should help you: