Functions are reusable blocks of code that perform a specific task. In Python, functions help organize code, improve readability, and enable reusability. Python supports both built-in and user-defined functions.
1. Defining and Calling Functions
Functions in Python are defined using the def
keyword, followed by the function name and parentheses ()
. The function body is indented, and the return
statement can be used to send back a result.
Example of a Simple Function:
def greet(): print("Hello, welcome to Python!") greet()
Output:
Hello, welcome to Python!
2. Function Parameters and Arguments
Functions can accept parameters to process input values dynamically.
Example:
def greet(name): print("Hello, " + name + "!") greet("Alice") greet("Bob")
Output:
Hello, Alice! Hello, Bob!
Multiple Parameters:
def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8
3. Default Parameters
Python allows setting default values for parameters if no argument is provided.
def greet(name="Guest"): print("Hello, " + name + "!") greet() # Output: Hello, Guest! greet("Alice") # Output: Hello, Alice!
4. Keyword Arguments
Python allows passing arguments using keyword-value pairs, making the function call clearer.
def introduce(name, age): print(f"My name is {name} and I am {age} years old.") introduce(age=25, name="Alice")
5. Arbitrary Arguments (*args and **kwargs)
Using *args (Multiple Positional Arguments)
*args
allows passing multiple arguments as a tuple.
def sum_numbers(*numbers): total = sum(numbers) print("Sum:", total) sum_numbers(5, 10, 15) # Output: Sum: 30
Using **kwargs (Multiple Keyword Arguments)
**kwargs
allows passing multiple keyword arguments as a dictionary.
def display_info(**info): for key, value in info.items(): print(f"{key}: {value}") display_info(name="Alice", age=25, city="New York")
6. Returning Values from a Function
The return
statement allows a function to send back a result.
def multiply(a, b): return a * b result = multiply(4, 5) print(result) # Output: 20
7. Lambda Functions (Anonymous Functions)
Lambda functions are small, anonymous functions defined using the lambda
keyword.
square = lambda x: x * x print(square(5)) # Output: 25
Lambda functions can have multiple parameters:
add = lambda a, b: a + b print(add(3, 7)) # Output: 10
8. Recursive Functions
A recursive function is a function that calls itself.
def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(factorial(5)) # Output: 120
9. Scope of Variables in Functions
Python variables have different scopes:
- Local Scope: Variables declared inside a function are local to that function.
- Global Scope: Variables declared outside a function are accessible globally.
x = 10 # Global variable def example(): y = 5 # Local variable print(y) example() print(x) # Output: 10
10. Using Functions with Map, Filter, and Reduce
map() Function:
The map()
function applies a function to all elements in an iterable.
numbers = [1, 2, 3, 4] squared = list(map(lambda x: x * x, numbers)) print(squared) # Output: [1, 4, 9, 16]
filter() Function:
The filter()
function filters elements based on a condition.
numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # Output: [2, 4, 6]
reduce() Function:
The reduce()
function applies a function cumulatively to all elements.
from functools import reduce numbers = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, numbers) print(product) # Output: 24
Functions in Python enhance code organization, reusability, and efficiency. Mastering function concepts, from basic definitions to advanced techniques like recursion and lambda functions, is essential for writing clean and effective Python programs.