The lambda statement in Python is used to create small anonymous functions, also known as lambda functions. These functions can have any number of arguments but only one expression. They are often used for short, simple operations and can be defined in a single line.
# Basic lambda function
# Define a lambda function to add two numbers
add = lambda a, b: a + b
# Call the lambda function
result = add(5, 3)
print(result) # Output: 8
# Lambda function with no parameters
# Define a lambda function that takes no parameters
say_hello = lambda: "Hello, world!"
# Call the lambda function
print(say_hello()) # Output: Hello, world!
# Using lambda function inside another function
def apply_operation(x, y, operation):
return operation(x, y)
# Call the function with a lambda function as an argument
result = apply_operation(5, 3, lambda a, b: a * b)
print(result) # Output: 15
# Lambda function with a single parameter
# Define a lambda function to square a number
square = lambda x: x ** 2
# Call the lambda function
print(square(4)) # Output: 16
# Define a function with a default parameter
def greet(name="Guest"):
print(f"Hello, {name}!")
# Call the function without providing a parameter
greet() # Output: Hello, Guest!
# Call the function with a parameter
greet("Alice") # Output: Hello, Alice!
The def
statement in Python is used to define a function.
# Define a function
def greet(name):
print(f"Hello, {name}!")
# Call the function
greet("Alice") # Output: Hello, Alice!
# Define a function with parameters and a return value
def add(a, b):
return a + b
# Call the function and print the result
result = add(5, 3) # result is 8
print(result) # Output: 8
The return
statement in Python is used to exit a function and optionally pass a value back to the caller. It is used to return the result of a function's execution.
# Returning a value from a function
def add(a, b):
return a + b
# Call the function and store the result
result = add(5, 3)
print(result) # Output: 8
# Returning multiple values from a function
def get_coordinates():
x = 10
y = 20
return x, y
# Call the function and unpack the returned tuple
x_coord, y_coord = get_coordinates()
print(x_coord, y_coord) # Output: 10 20
# Returning nothing from a function
def greet(name):
print(f"Hello, {name}!")
return
# Call the function
greet("Alice") # Output: Hello, Alice!