 Darryl Dan - 3 years ago 93
Python Question

# using lambda together with a condition statement

This is my code to check if the value of getBonus() is above 5000 after i add 100 to the numder using lambda. lets say if i must use lambda method, how can i use a condition statement such as if-else to check whether the value is more or lesser than 5000?

`````` bonus=1000
getBonus= lambda x:x+100
if x>5000:
return x+bonus*2
else:
return x+bonus
print getBonus(3000)
print getBonus(6000)
``````

it keeps saying return is out of the function which i assumed it is referring to the lambda expression Jean-Fran&#231;ois Fabre

Your code is incorrect but I'm getting the idea.

This is possible with a lambda but a bit twisted (because you have to test x against 5000 but added 100. Using a ternary is the key:

``````bonus=1000
getBonus = lambda x: x+100+bonus*2 if x>5100 else x+100+bonus
print(getBonus(3000))
print(getBonus(4950))
print(getBonus(4900))
print(getBonus(6000))
``````

result:

``````4100
6050
6000
8100
``````

I think I got the formula & test OK. Tests indicate so, but just the fact that I'm doubting means that creating a lambda for that is not a very good idea unless you can't do otherwise.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download