without arguments

Introduction:

  • In Python, you can define a lambda function without any arguments by using an empty parameter list.

Example:

  • Consider the following lambda function that has no arguments and always returns "Hello World":

    python
    lambda: "Hello World"
    
    • This lambda function returns "Hello World" every time it is called.

Examples:

  1. Lambda Function without Arguments that Always Returns "Hello World":
    • In the following program, we define a lambda function without any arguments, which always returns the string value "Hello World". We assign the lambda function to a variable named greeting, call the lambda function with greeting(), and print the returned value.

      python
      greeting = lambda: "Hello World"
      
      # Call the lambda function
      result = greeting()
      print(result)
      
    • Output:

       
      Hello World
      
  2. Lambda Function without Arguments that Always Returns 3.14:
    • In the following program, we define a lambda function without any arguments, which always returns the floating-point value 3.14. We assign the lambda function to a variable named pi.

      python
      pi = lambda: 3.14
      
      # Call the lambda function
      result = pi()
      print(f"PI is {result}")
      
    • Output:

       
      PI is 3.14
      

Exercises:

  1. Lambda Function Returning a Greeting:
    • Define a lambda function without any arguments that always returns the string "Welcome to Python!".

      python
      welcome = lambda: "Welcome to Python!"
      
      # Call the lambda function
      print(welcome())
      
  2. Lambda Function Returning a Fixed Number:
    • Define a lambda function without any arguments that always returns the number 42.

      python
      answer = lambda: 42
      
      # Call the lambda function
      print(answer())
      

Summary:

  • In this tutorial, we learned how to define a lambda function without arguments and how such a lambda function works, with the help of example programs. Lambda functions are useful for returning constant values or performing simple operations without needing to define a full function. Practice writing lambda functions to get comfortable using them in your Python programs!