Python Functions
In Python, a function is a block of code that only runs when it is called. Functions help in breaking the program into smaller, modular, and reusable parts. Python functions can have parameters (arguments) that allow you to pass data into the function and return a value using the return
statement.
Python functions are an essential part of writing clean and efficient code. They allow for code reusability, modularity, and better organization of your programs. By understanding functions, parameters, return values, and other related concepts, you can write more efficient and readable Python programs.
What is a Function?
- A function is defined using the
def
keyword followed by the function name and parentheses()
. - The code block within every function starts with a colon
:
and is indented. - Functions may or may not return a value. If they do, the
return
statement is used. - Functions help avoid code duplication and make the code easier to maintain.
1. Defining and Calling a Function
# Example: Defining a Function
def greet():
print("Hello, welcome to Python Functions!")
# Calling the function
greet()
Output
Functions with Parameters
Functions can accept parameters that provide additional information for processing.
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice")
greet_user("Bob")
Output
Functions with Return Values
Functions can return values using the return
statement. This allows functions to send back a result to the caller.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 7)
print("Sum:", result)
Output
Default Arguments
Python allows function parameters to have default values, which are used if no argument is passed during the function call.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("John")
greet()
Output
Keyword Arguments
Python functions support keyword arguments, which allow you to specify the parameter names during function calls.
def display_info(name, age):
print(f"Name: {name}, Age: {age}")
display_info(age=30, name="Alice")
Output
Variable-Length Arguments
You can pass a variable number of arguments to a function using *args
for non-keyword arguments and **kwargs
for keyword arguments.
def sum_all(*args):
return sum(args)
print("Sum:", sum_all(1, 2, 3, 4))
Output
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda
keyword. They can have any number of arguments but only one expression.
Syntax
lambda arguments: expression
Examples:
1. Basic Example
# Regular function
def add(a, b):
return a + b
# Lambda function
add_lambda = lambda a, b: a + b
print(add_lambda(3, 5))
Output
2. Single Argument
square = lambda x: x ** 2
print(square(4))
Output
3. Multiple Arguments
multiply = lambda x, y: x * y
print(multiply(3, 7))
Output
When to use Lambda Functions
- When you need a small, one-time use(throwaway) function.
- In places where a full function definition would make the code less readable.
- When you want to pass a function as an argument to another function.
- For small operations in functional programming contexts like map(), filter(), and sorted()
Limitations
- ambda functions can have only one expression (no statements or multiple lines).
- They can be less readable if overused or made too complex.