Functions in Python
? Functions in Python
A function in Python is a block of reusable code that performs a specific task. Functions help in organizing code, avoiding repetition, and improving readability.
Basic Syntax of a Function:
def function_name(parameters): # Block of code return resultdefis a keyword used to define a function.function_nameis the name of the function.parameters(optional) are the inputs the function takes.The code block inside the function defines what the function does.
The
returnstatement (optional) specifies the value that the function will return.
? 1. Defining a Function
Here’s a simple function that prints a message:
def greet(): print("Hello, world!")Usage: Call the function using its name:
greet()Output:
Hello, world!
? 2. Function with Parameters
A function can take parameters (inputs) that allow it to perform operations on the data provided.
def greet(name): print(f"Hello, {name}!")Usage: Pass an argument when calling the function:
greet("Alice")Output:
Hello, Alice!
? 3. Function with Return Value
A function can return a value to the caller using the return statement.
def add(a, b): return a + bUsage: The result of the function can be stored in a variable or used directly:
result = add(3, 4)print(result)Output:
7
? 4. Default Arguments
You can define default values for parameters. If the caller does not provide a value for those parameters, the default value is used.
def greet(name="Guest"): print(f"Hello, {name}!")Usage:
greet() # Uses default argumentgreet("Alice") # Uses provided argumentOutput:
Hello, Guest!Hello, Alice!
? 5. Keyword Arguments
You can pass arguments to a function by explicitly naming them. This is called keyword arguments.
def greet(name, age): print(f"Hello, {name}! You are {age} years old.")Usage:
greet(age=25, name="Alice")Output:
Hello, Alice! You are 25 years old.Explanation: The order of arguments doesn’t matter when using keyword arguments.
? 6. Arbitrary Arguments (*args and **kwargs)
Sometimes you may not know how many arguments you will pass to a function. You can use *args (for non-keyword arguments) and **kwargs (for keyword arguments) to handle such cases.
*args (Non-Keyword Arguments)
def greet(*args): for name in args: print(f"Hello, {name}!")Usage:
greet("Alice", "Bob", "Charlie")Output:
Hello, Alice!Hello, Bob!Hello, Charlie!Explanation:
*argscollects all the positional arguments into a tuple.
**kwargs (Keyword Arguments)
def greet(**kwargs): for name, age in kwargs.items(): print(f"Hello, {name}! You are {age} years old.")Usage:
greet(Alice=25, Bob=30, Charlie=22)Output:
Hello, Alice! You are 25 years old.Hello, Bob! You are 30 years old.Hello, Charlie! You are 22 years old.Explanation:
**kwargscollects all keyword arguments into a dictionary.
? 7. Lambda Functions (Anonymous Functions)
A lambda function is a small, anonymous function defined with the lambda keyword. It can have any number of parameters but only one expression.
Syntax:
lambda arguments: expressionExample:
multiply = lambda x, y: x * yresult = multiply(3, 4)print(result)Output:
12Explanation:
lambda x, y: x * ydefines a function that multiplies two numbers.
? 8. Recursion in Functions
A function can call itself, which is known as recursion. This is useful for problems that can be broken down into smaller, similar sub-problems.
Example: Factorial Calculation
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)Usage:
print(factorial(5))Output:
120Explanation: The function keeps calling itself until
nreaches0.
? 9. Function Documentation (docstring)
Functions can have a docstring (documentation string) to describe their purpose, parameters, and return values. The docstring is written in between triple quotes ("""docstring""").
def add(a, b): """ This function adds two numbers. Parameters: a (int, float): The first number. b (int, float): The second number. Returns: int, float: The sum of a and b. """ return a + bAccessing Docstring: You can access the function’s docstring using
help()or.__doc__.
print(add.__doc__)Output:
This function adds two numbers.Parameters:a (int, float): The first number.b (int, float): The second number.Returns:int, float: The sum of a and b.
? 10. Functions as Arguments
You can pass a function as an argument to another function.
def apply_function(func, value): return func(value)def square(x): return x * xresult = apply_function(square, 5)print(result)Output:
25Explanation: The
apply_functiontakes another function (square) and applies it to the value5.
Summary of Functions in Python:
| Feature | Description |
|---|---|
| Defining a Function | Use def to define a function. |
| Parameters | Functions can take parameters for dynamic input. |
| Return Value | Functions can return a result using return. |
| Default Arguments | You can set default values for parameters. |
| Keyword Arguments | Call functions with named parameters. |
*args and **kwargs | Handle variable numbers of arguments. |
| Lambda Functions | Small anonymous functions defined using lambda. |
| Recursion | Functions that call themselves. |
| Docstring | Describes the function’s purpose and usage. |
| Functions as Arguments | Functions can accept other functions as arguments. |
By using these techniques, you can create reusable and efficient functions in Python. Let me know if you'd like more examples or clarifications! ?