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 else within a lambda function to choose a return value based on a condition.

Syntax:

  • The syntax for a Python lambda function with if else:

    python
    lambda <arguments>: <value_1> if <condition> else <value_2>
    
    • value_1 is returned if condition is true, otherwise value_2 is returned.
  • For nested if else:

    python
    lambda <arguments>: <value_1> if <condition_1> else (<value_2> if <condition_2> else <value_3>)
    
    • value_1 is returned if condition_1 is true. If not, condition_2 is checked. If condition_2 is true, value_2 is returned; otherwise, value_3 is returned.

Examples:

  1. 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.

      python
      x = lambda n: n**2 if n % 2 == 0 else n**3
      
      print(x(4))  # Output: 16
      print(x(3))  # Output: 27
      
  2. 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.

      python
      x = 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:

  1. 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.

      python
      check_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
      
  2. 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.

      python
      calculate_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 else or nested if else in 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!