0% found this document useful (0 votes)
4 views19 pages

01 Python Functions Deep Dive

The document provides a comprehensive overview of Python functions, focusing on parameters, *args, and **kwargs for handling variable-length arguments. It explains the importance of functions in code organization, reusability, and avoiding repetition, while also demonstrating practical examples of using these features. Key guidelines for function naming and parameter usage are also highlighted to enhance code clarity and maintainability.

Uploaded by

skmandokhail2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

01 Python Functions Deep Dive

The document provides a comprehensive overview of Python functions, focusing on parameters, *args, and **kwargs for handling variable-length arguments. It explains the importance of functions in code organization, reusability, and avoiding repetition, while also demonstrating practical examples of using these features. Key guidelines for function naming and parameter usage are also highlighted to enhance code clarity and maintainability.

Uploaded by

skmandokhail2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Functions Deep Dive

Mastering Parameters, *args, and **kwargs


Slide 2: What Are Functions?
• The Building Blocks of Python
• Reusable code blocks that perform specific tasks
• Input → Processing → Output structure
• Help avoid code repetition (DRY principle)
• Make code more organized and readable

• Basic Syntax

• def function_name(parameters):
• """Docstring describing the function"""
• # Function body
• return value # Optional
Slide 3: Basic Function Examples
• Simple Function

• def greet(name):
• """Return a greeting message"""
• return f"Hello, {name}!"

• print(greet("Alice")) # Hello, Alice!

• Function with Multiple Parameters

• def add_numbers(a, b):


• """Add two numbers"""
• return a + b

• result = add_numbers(5, 3) # Returns 8


Slide 4: The Problem: Unknown Number of
Arguments
• What happens when You don't know how many arguments will be passed?
• You want flexibility in function parameters?
• You need to pass arguments from another function?

• Traditional Approach Limitations

• # What if we want to add 3, 4, or 5 numbers?


• def add_three(a, b, c):
• return a + b + c

• def add_four(a, b, c, d):
• return a + b + c + d
• # This gets messy quickly!
Slide 5: Introducing args
• Variable-Length Positional Arguments
• The * is the unpacking operator
• Can be any name, but *args is convention

• def sum_all(*args):
• """Sum any number of arguments"""
• total = 0
• for number in args:
• total += number
• return total

• print(sum_all(1, 2, 3)) #6
• print(sum_all(1, 2, 3, 4, 5)) # 15
Slide 6: args in Action
• More Practical Examples

• # Example 1: Flexible averaging


• def average(*args):
• if len(args) == 0:
• return 0
• return sum(args) / len(args)

• # Example 2: Concatenating strings


• def concatenate(*args, separator=" "):
• return [Link](str(arg) for arg in args)

• print(average(10, 20, 30)) # 20.0


• print(concatenate("Hello", "World", separator="-")) # Hello-World
• Function arguments can be passed explicitly by name, and this means
that the order of arguments specified in the caller can be different
than the order of arguments with which the function was defined:
• >>> def f(a, b=2):
• ... return a + b, a - b
• ...
• >>> x, y = f(b=5, a=2)
• >>> print x
•7
• >>> print y
• -3
• A list or tuple can be passed to a function that requires individual
positional arguments by unpacking them
Passing Arguments Dynamically
• def multiply(a, b, c):
• return a * b * c

• numbers = [2, 3, 4]
• print(multiply(*numbers))
• # Equivalent to multiply(2, 3, 4)
Passing Arguments Dynamically
• >>> def f(a, b):
• ... return a + b
• ...
• >>> c = (1, 2)
• >>> print f(*c)
•3
• a dictionary can be unpacked to deliver keyword arguments
• >>> def f(a, b):
• ... return a + b
• ...
• >>> c = {'a':1, 'b':2}
• >>> print f(**c)
•3
Introducing kwargs
• Variable-Length Keyword Arguments
• **kwargs collects extra keyword arguments as a dictionary

• The ** is the unpacking operator for dictionaries

• kwargs stands for "keyword arguments"


Introducing kwargs
• Example

• def display_info(**kwargs):
• """Display any key-value pairs"""
• for key, value in [Link]():
• print(f"{key}: {value}")

• display_info(name="Alice", age=30, city="New York")


• Output:
• name: Alice
• age: 30
• city: New York
Combining *args and **kwargs
• >>> def f(*a, **b):
• ... return a, b
• ...
• >>> x, y = f(3, 'hello', c=4, test='world')
• >>> print x
• (3, 'hello')
• >>> print y
• {'c':4, 'test':'world'}
• Here arguments not passed by name (3 & 'hello') are stored in the
tuple a,
• and arguments passed by name (c & test) are stored in the dictionary
b.
When and How to Use *args and **kwargs

• *Use args when:


• ✓ You need a variable number of positional arguments
• ✓ You're wrapping or extending another function
• ✓ You're creating utility functions (like sum, max)

• **Use kwargs when:


• ✓ You need optional configuration parameters
• ✓ You're building APIs or libraries
• ✓ You need to pass through arguments to other functions
Important Guidelines:

• Always use clear, descriptive function names

• Include docstrings explaining parameter expectations

• Don't overuse – sometimes explicit parameters are better

• *args and **kwargs should typically come last

You might also like