with if else
Introduction:
- In Python, lambda functions are small anonymous functions that can take any number of arguments but have only one expression. You can use
if elsewithin a lambda function to choose a return value based on a condition.
Syntax:
The syntax for a Python lambda function with
if else:pythonlambda <arguments>: <value_1> if <condition> else <value_2>value_1is returned ifconditionis true, otherwisevalue_2is returned.
For nested
if else:pythonlambda <arguments>: <value_1> if <condition_1> else (<value_2> if <condition_2> else <value_3>)value_1is returned ifcondition_1is true. If not,condition_2is checked. Ifcondition_2is true,value_2is returned; otherwise,value_3is returned.
Examples:
- Lambda Function with If-Else Condition:
This lambda function returns the square of the number if it is even, otherwise, it returns the cube of the number.
pythonx = lambda n: n**2 if n % 2 == 0 else n**3 print(x(4)) # Output: 16 print(x(3)) # Output: 27
- Lambda Function with Nested If-Else Condition:
This lambda function returns the number as is if it is divisible by 10, the square of the number if it is even, otherwise, it returns the cube of the number.
pythonx = lambda n: n if n % 10 == 0 else (n**2 if n % 2 == 0 else n**3) print(x(4)) # Output: 16 print(x(3)) # Output: 27 print(x(10)) # Output: 10
Exercises:
- Check if a Number is Positive, Negative, or Zero:
Define a lambda function that returns "Positive" if a number is greater than 0, "Negative" if it is less than 0, and "Zero" if it is 0.
pythoncheck_number = lambda n: "Positive" if n > 0 else ("Negative" if n < 0 else "Zero") print(check_number(10)) # Output: Positive print(check_number(-5)) # Output: Negative print(check_number(0)) # Output: Zero
- Calculate Discount Based on Amount:
Define a lambda function that returns a 10% discount if the amount is greater than 100, a 5% discount if it is between 50 and 100, and no discount if it is less than 50.
pythoncalculate_discount = lambda amount: amount * 0.9 if amount > 100 else (amount * 0.95 if amount >= 50 else amount) print(calculate_discount(150)) # Output: 135.0 print(calculate_discount(75)) # Output: 71.25 print(calculate_discount(40)) # Output: 40
Summary:
- In this tutorial, we learned how to use
if elseor nestedif elsein lambda functions to conditionally return values. Lambda functions are useful for short, simple operations that you want to define quickly and use immediately. Practice writing lambda functions with conditions to get comfortable using them in your Python programs!