Python - Functions
Functions in Python are reusable blocks of code that perform a specific task. They are central to structuring programs in a clean and modular way.
1. Defining and Calling Functions
Functions are defined using the def keyword, followed by the function name and parentheses. You can then call them from anywhere in your code.
python
# Defining a simple function def greet(): print("Hello, world!") # Calling the function greet()
2. Function Arguments
You can pass values to functions through arguments. Python supports:
- Default Arguments
- Keyword Arguments
- Arbitrary Arguments (*args and **kwargs)
python
# Default argument def greet(name="Guest"): print("Hello", name) greet() greet("Alice") # Arbitrary positional arguments def add(*numbers): total = sum(numbers) print("Sum:", total) add(1, 2, 3, 4) # Arbitrary keyword arguments def print_info(**info): for key, value in info.items(): print(f"{key}: {value}") print_info(name="Raj", age=25)
3. Return Statement
The return statement is used to send a result back to the caller.
python
def square(x): return x * x result = square(5) print("Square is:", result)
4. Lambda Functions
Lambda functions are anonymous one-line functions, useful for short operations.
python
double = lambda x: x * 2 print(double(10)) # Output: 20
5. Recursion
Recursion is when a function calls itself to solve a problem. Base condition is crucial to prevent infinite recursion.
python
# Recursive factorial function def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5)) # Output: 120
Pros and Cons of Using Functions
Pros:
- Code reusability
- Modularity
- Improved readability
- Easy debugging and testing
Cons:
- Too many small functions can cause complexity
- Improper use of recursion can lead to memory issues
- Function overhead for very small tasks