Functions
✕Concept of Functions
- A block of reusable and modular code that performs a specific task
- Helps to break down complex problems into smaller, manageable pieces
- Improves code readability and maintainability
- Has argument (input), code (logic), return value (output)
- Doesn't execute until it's called/invoked
- To invoke, we use its name followed by
argumentsin parentheses() - def function_name(parameters):{expression}return value
Syntax:
Example of a Function
def greet(name):return f"Hello, {name}!"message = greet("Rabi")print(message)# Hello, Rabi!def calculate_area(radius):pi = 3.14area = pi * radius ** 2return arearesult = calculate_area(5)print(result)# 78.5
Example:
Docstring
- Used for documenting a function's purpose, parameters and return value
- Added inside triple quotes
"""immediately after function definition - Helps improve code readability and maintainability
- AI tools can automatically generate doc strings based on code and comments
- Can be accessed using
__doc__attribute def greet(name):"""Returns a greeting message."""return f"Hello, {name}!"# Hello, Alice!
Example:
Variable Scope
- The region of code where a variable is defined and can be accessed
- Global: Defined outside of a function
- Non-local: Defined in an enclosing function (for nested functions)
- Local: Defined inside a function
- When variable is called, Python first looks in local, non-local and finally global scope.
- If variable is not found in any of these scopes, it raises a
NameError - We only get read access for variables in non-local and global scope.
- To get write access, we need to use
nonlocalandglobalkeywords respectively
Types of Variable Scope:
Variable Scope Example
x = 10 # Global variabledef my_function():x = 5 # Local variableprint("Inside function, x =", x)my_function()print("Outside function, x =", x)# Output: # Inside function, x = 5 # Outside function, x = 10
Default Value
- Argument of function can be made optional by assigning default value
- If argument is not provided during function call, default value is used
- Default value for mutable data has to be assigned None
def greet(name="Python"):return f"Hello, {name}!"print(greet())# Hello, Python!print(greet("Data Engineer"))# Hello, Data Engineer!
Example:
Lambda Functions
- One-line, Anonymous functions without name
- Used for small, one-time operations. Often used in map, filter and reduce functions
square = lambda x: x ** 2print(square(5))# 25sum_diff = lambda x, y: (x + y, x - y)print(sum_diff(3, 4))# (7, -1)even_chk = lambda x: 'Yes' if x % 2 == 0 else 'No'print(even_chk(4))# Yesprint(even_chk(5))# No
Examples:
Filter Function
- Used to filter elements from a sequence based on a function that returns True/False
- filter(function, sequence) # Function evaluates each item and returns only those evaluated as True
numbers = [1, 2, 3, 4, 5]even_checker = lambda x: x % 2 == 0even_numbers = list(filter(even_checker, numbers))print(even_numbers)# [2, 4]age_list = [15, 22, 30, 17, 40]adults = list(filter(lambda x: x >= 18, age_list))print(adults)# [22, 30, 40]
Syntax:
Example:
Map Function
- Apply a function to all items of a sequence and return a new sequence with results
- map(function, sequence) # Function is applied to each item and a new sequence is returned
numbers = [1, 2, 3, 4, 5]square_function = lambda x: x ** 2squared_numbers = list(map(square_function, numbers))print(squared_numbers)# [1, 4, 9, 16, 25]num_values = ['1', '2', '3']int_values = list(map(int, num_values))print(int_values)# [1, 2, 3]
Syntax:
Example:
Reduce Function
- Apply function recursively to the items of a sequence, reducing to a single value
- reduce(function, sequence) # Function is applied recursively to the items from left to right, giving a single value
from functools import reducenumbers = [1, 2, 3, 4]product = reduce(lambda x, y: x * y, numbers)print(product)# 24numbers = [1, 2, 3, 4]sum = reduce(lambda x, y: x + y, numbers)print(sum)# 10
Syntax:
Example:
Args
- Used to pass a n number of non-keyword arguments to a function
- All extra arguments are packed into a tuple in
args def product_all(*args):total = 1for num in args:total = total * numreturn totalresult = product_all(1, 2, 3, 4)print(result)# 24
Example:
Kwargs
- Used to pass a n number of keyword arguments to a function
- All extra keyword arguments are packed into a dictionary in
kwargs def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=30, city="New York")# Output: # name: Alice # age: 30 # city: New York
Example:
