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
<
note you can use several else...if statements in your lambda definition:
f = lambda x: 1 if x>0 else 0 if x ==0 else -1
Probably the worst python line I've written so far:
f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])
If x == 2 you print,
if x != 2 you raise.
You can easily raise an exception in a lambda, if that's what you really want to do.
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
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 solution for the given scenerio is:
f = lambda x : x if x == 2 else print("number is not 2")
f(30) # number is not 2
f(2) #2
why don't you just define a function?
def f(x):
if x == 2:
print(x)
else:
raise ValueError
there really is no justification to use lambda in this case.
what you need exactly is
def fun():
raise Exception()
f = lambda x:print x if x==2 else fun()
now call the function the way you need
f(2)
f(3)