Module 5: Functions and Modules
• Topics:
• - Function arguments (*args, **kwargs)
• - Anonymous functions (lambda)
• - Standard Python Modules: random, os, sys
Function Arguments Overview
• Functions can accept different types of
arguments:
• - Positional arguments
• - Keyword arguments
• - Variable length arguments (*args, **kwargs)
*args in Python
• *args is used to pass a variable number of
positional arguments to a function.
• Example:
• def add_numbers(*args):
• return sum(args)
• print(add_numbers(1,2,3,4)) # Output: 10
**kwargs in Python
• **kwargs is used to pass a variable number of
keyword arguments.
• Example:
• def print_details(**kwargs):
• for key, value in [Link]():
• print(key, value)
• print_details(name='John', age=25)
Anonymous Functions (lambda)
• Lambda functions are small anonymous
functions defined using the keyword lambda.
• Syntax: lambda arguments: expression
• Example:
• add = lambda x, y: x + y
• print(add(5, 3)) # Output: 8
Advantages of Lambda Functions
• - Concise and easy to use
• - Useful for short operations
• - Often used with map(), filter(), reduce()
Standard Python Module: random
• The random module is used for generating
random numbers.
• Examples:
• import random
• print([Link](1, 10))
• print([Link](['apple', 'banana',
'cherry']))
Standard Python Module: os
• The os module provides functions to interact
with the operating system.
• Examples:
• import os
• print([Link]()) # Get current directory
• [Link]('test_folder') # Create new folder
Standard Python Module: sys
• The sys module provides system-specific
parameters and functions.
• Examples:
• import sys
• print([Link]) # Python version
• print([Link]) # Command-line arguments
Summary
• - *args and **kwargs allow flexible arguments
in functions
• - Lambda functions create anonymous
functions
• - random, os, sys are standard Python
modules for various tasks