0% found this document useful (0 votes)
8 views

cs ppt class 11

The document explains various types of functions in Python, including simple functions, functions with parameters, default arguments, arbitrary arguments (*args and **kwargs), recursive functions, and higher-order functions. It emphasizes the importance of function simplicity, reusability, and flexibility, providing examples and key points for each type. Additionally, it covers concepts like nested functions, type checking, and the use of lambda functions for short tasks.

Uploaded by

itskunj11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

cs ppt class 11

The document explains various types of functions in Python, including simple functions, functions with parameters, default arguments, arbitrary arguments (*args and **kwargs), recursive functions, and higher-order functions. It emphasizes the importance of function simplicity, reusability, and flexibility, providing examples and key points for each type. Additionally, it covers concepts like nested functions, type checking, and the use of lambda functions for short tasks.

Uploaded by

itskunj11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

SIMPLE FUNCTION

A simple function is a function that performs a basic task, takes input (arguments), processes it, and
returns an output. It doesn't involve complex logic, just a straightforward operation.

EXAMPLE in Python:

Def add_numbers(a, b):

return a + b

 Input: Two numbers (a and b).


 Task: Adds the numbers together.
 Output: Returns the sum.

Key Points:

 Simplicity: Focuses on one action.


 Reusability: Can be used repeatedly with different inputs.
 Readability: Easy to understand and maintain.

In short, a simple function encapsulates a single, clear task in a reusable block of code.
(ARGUMENT) ONLY PARIMETER

In a function, parameters are variables listed in the function definition, while arguments are
the actual values passed to the function when it is called.

 Parameter: A placeholder used in the function definition to accept values.


 Argument: The actual value passed to the parameter when calling the function.

# Here “name” is a parameter and “Alice” is the argument

In this case:

 name is the parameter.


 "Alice" is the argument passed to the function when it is called.

Key Point:

 Parameter: Defined in the function signature.


 Argument: Provided when calling the function.
MULTIPLE PARIMETER
In a function, multiple parameters allow you to pass more than one value to the function. You can
define a function with more than one parameter to perform more complex tasks.

#Here ‘a’, ’b’, ’c’ are multiple parameters and 2 , 3, and 4 are the arguments passed to the
parameters.

#Output: 9

Example Breakdown:

 The function add has 3 parameters: a, b, and c.


 When calling the function, the arguments 2, 3, and 4 are passed to these parameters.

Key Points:

 Multiple Parameters: You can define multiple parameters in the function signature
to handle different inputs.
 Arguments: You provide the corresponding arguments when calling the function, and
they are assigned to the respective parameters.

Multiple parameters allow the function to handle more complex logic with multiple inputs.
DEFAULT ARGUMENTS
Default arguments allow you to define a function with default values for one or more parameters. If
the caller does not provide a value for those parameters, the default value is used.

Output:

Example Breakdown:

 In the function greet, name defaults to "Guest", and age defaults to 25.
 If you don’t provide a value when calling greet(), the function uses the default
values.

Key Points:

 Default Argument: A parameter in a function definition that has a predefined value.


 When Provided: If the caller provides a value for the parameter, that value is used.
 When Not Provided: If the caller does not provide a value, the default value is used.

This makes your functions more flexible and reduces the need for the caller to specify every value.
(ARGS) ARBITRATY NO. OF
ARGUMENTS

Arbitrary number of arguments allows a function to accept an undefined or variable


number of arguments. This is useful when you don’t know in advance how many arguments
will be passed to the function.

You can achieve this using the *args syntax in Python.

Output:

Example Breakdown:

 *names collects "Alice", "Bob", and "Charlie" into a tuple.


 The function loops through names and greets each person.

Key Points:

 *args: Collects additional positional arguments passed to the function into a tuple.
 Flexible: The function can accept any number of arguments.
 Accessing Arguments: Inside the function, args behaves like a tuple

DO YOU NOW Why WE Use *args NOT OTHER FUNCTION ?

 It gives you the flexibility to pass any number of arguments to the function without
needing to specify each one.
 It's particularly useful when you're not sure how many arguments a function might
need to handle.
(KWARGS)ARBITARY NO. OF
KEYWORD ARGUMENTS

Arbitrary number of keyword arguments, often referred to as **kwargs, allows a function to


accept a variable number of keyword arguments (i.e., named arguments). The keyword arguments
are collected into a dictionary, where the keys are the argument names and the values are the
corresponding argument values.

Output:

Example Breakdown:

 The function print_info uses **kwargs to collect the arguments name, age, and
city.
 These arguments are stored as key-value pairs in the info dictionary.

Key Points:

 **kwargs: Collects arbitrary keyword arguments into a dictionary.


 Flexible: You can pass any number of named arguments to the function.
 Accessing Arguments: Inside the function, kwargs is a dictionary, and you can
access the values using the keys.

Why Use **kwargs?

 It allows you to pass a flexible number of named arguments to a function, making the
function more versatile.
 Useful when the function needs to handle multiple named arguments that can vary
each time the function is called.

Key Difference Between *args and **kwargs:

 *args: Collects a variable number of positional arguments as a tuple.


 **kwargs: Collects a variable number of keyword arguments as a dictionary.
RETURNING A VALUE FROM A
FUNCTION
Returning a value from a function allows the function to send back a result to the caller
after it performs its task. This makes the function more useful because it can provide useful
information or outcomes that can be used later in the program.

Syntax:

 Use the return keyword followed by the value or expression you want to return.

Example:

Output: #8

Example Breakdown:

 The function add performs an addition of two numbers and then returns the result.
 The returned value is captured in the variable sum_result and printed.

Key Points:

 return: The keyword used to exit the function and send back a value to the caller.
 A function can return a value of any type (integer, string, list, etc.).
 Optional: If no return is specified, the function returns None by default

Why Use return?

 Returning a value makes the function reusable and allows the output to be passed
along for further computation.
 Without a return statement, a function cannot provide any outcome, limiting its use.
(ANONYMOUS FUNCTIONS) LAMBDA
FUNCTION
Anonymous functions (also known as lambda functions) are small, one-liner functions in
Python that are defined without a name. They are often used for short tasks where you don’t
want to define a full function.

Syntax:

lambda arguments: expression

 lambda: Keyword that defines the function.


 arguments: Input parameters (can be one or more).
 expression: A single expression that the function evaluates and returns.
Example:

Output: #8

Example Breakdown:

 lambda a, b: a + b is a lambda function that takes two parameters a and b, adds


them together, and returns the result.
 The function is assigned to the variable add, and called just like any other function.

Example with map():


numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
In this case, the lambda function is used to square each number in the list numbers.

When to Use Lambda Functions?

 Short tasks: For operations that can be written in a single line and used only once.
 In functions like map(), filter(), and sorted(): Lambda functions are often used
when passing a short function as an argument.

Limitations:

 Single expression: Lambda functions cannot have multiple expressions or statements,


limiting their complexity.
 Readability: While useful for short tasks, overusing lambda functions in complex
operations can make the code harder to read.
NESTED FUNCTION
A nested function is a function defined inside another function. The inner function can be
used by the outer function, and it is typically used when you need to perform a specific task
that is only relevant within the outer function.

Syntax:

Result from inner function: # 8

Example Breakdown:

 The inner_function is defined inside outer_function.


 The inner function performs a simple addition, and its result is used within the outer
function.
 When outer_function() is called, it calls the inner_function and prints its result.

Why Use Nested Functions?

 Encapsulation: Helps in encapsulating functionality that doesn't need to be accessed


outside the outer function.
 Closures: Nested functions can access variables from the outer function’s scope,
which is useful in closures.

Example with Closure:

# Creating a closure:

Output: # 15

Key Points:

 Inner Function: A function defined inside another function.


 Access: The inner function is only accessible within the scope of the outer function.
 Encapsulation: Nested functions help encapsulate functionality that is only needed
inside the outer function.

Key Takeaway:

 In this closure example, the inner_function remembers the x value from its
surrounding environment (the outer function) even after the outer function has
finished executing.
(USING ARGS & RWARGS TOGETHER)
FUNCTION WITH VARIABLE NO. OF
ARGUMENT
 *args: Collects additional positional arguments (tuple).

 **kwargs: Collects additional keyword arguments (dictionary).

 Purpose: Allows functions to accept a variable number of arguments.

Function Syntax

 Syntax for *args (positional arguments)

Syntax for **kwargs (keyword arguments)

Using Both Together

Order of Parameters

 Key Rule: *args must appear before **kwargs.


 Example:

example_function :-(1, 2, 3, 4, 5, c='changed', d='extra')

Output:

#12

(3, 4, 5)

Changed
Explanation of the Example

 a and b are regular positional arguments.


 *args collects extra positional arguments (3, 4, 5).
 c has a default value, which is overridden by 'changed'.
 **kwargs collects the keyword argument d='extra'

Key Points

 *args captures extra positional arguments as a tuple.


 **kwargs captures extra keyword arguments as a dictionary.
 Order: *args first, **kwargs last.
 Default values for keyword arguments can be set and overridden.

Conclusion

 Combining *args and **kwargs provides a flexible way to handle functions with
variable arguments.
 This feature is especially useful in scenarios like logging, event handling, etc.

This layout covers key points with an example and explanation, making it easy for an audience to
understand the use of *args and **kwargs together in Python functions.
RECURSIVE FUNCTION
 A function that calls itself in order to solve smaller instances of the same problem.

 It breaks a problem down into simpler subproblems.

A recursive function has two main parts:

 Base Case: Stops the recursion, preventing infinite loops.


 Recursive Case: The function calls itself with a smaller problem.

Example 1: Factorial Function

 Problem: Find the factorial of a number nnn, denoted as n!n!n!.


o n!=n×(n−1)×(n−2)×...×1n! = n \times (n-1) \times (n-2) \times ... \times 1n!
=n×(n−1)×(n−2)×...×1

Recursive Formula:

 n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)!


 Base case: 0!=10! = 10!=1

Factorial Example Code

Example usage

result = factorial(5)

Output: #120

Step-by-Step Breakdown (Factorial of 5)

 Factorial(5): 5×Factorial(4)5 \times \text{Factorial(4)}5×Factorial(4)


 Factorial(4): 4×Factorial(3)4 \times \text{Factorial(3)}4×Factorial(3)
 Factorial(3): 3×Factorial(2)3 \times \text{Factorial(2)}3×Factorial(2)
 Factorial(2): 2×Factorial(1)2 \times \text{Factorial(1)}2×Factorial(1)
 Factorial(1): 1×Factorial(0)1 \times \text{Factorial(0)}1×Factorial(0)
 Factorial(0): 1 (Base Case)
Result: 5×4×3×2×1=1205 \times 4 \times 3 \times 2 \times 1 = 1205×4×3×2×1=120

Key Points About Recursion


 Base Case: Prevents infinite recursion and ensures termination.
 Recursive Call: Reduces the problem to a smaller instance.

 Recursion can sometimes lead to higher memory usage and slower performance for large
problems.
FUNCTION WITH TYPE PRINTING
 Printing or checking the data type of an argument inside a function.
 Useful for debugging, validation, and ensuring functions handle the correct types.

type() Function in Python

 The type() function returns the type of an object.

Syntax:

Using type() in Functions

 We can print the type of arguments passed to a function.


 Useful for checking and debugging the types of inputs.

Example 1: Function with Type Printing

# Example usage

print_type(5) # Output: Value: 5, Type: <class 'int'>

print_type("Hi") # Output: Value: Hi, Type: <class 'str'>

print_type([1, 2]) # Output: Value: [1, 2], Type: <class 'list'>

Explanation of Example

 print_type(5): Prints type as <class 'int'>.


 print_type("Hi"): Prints type as <class 'str'>.
 print_type([1, 2]): Prints type as <class 'list'>.

This demonstrates how type() shows the data type of the argument inside the function.

Example 2: Type Checking and Validation

 We can use type printing to validate arguments:


Example Usage:

check_type(5) # This is an integer!

check_type("text") # This is not an integer!

Key Points

 type() helps in inspecting the type of variables.


 Type printing can be useful for debugging and ensuring type safety in your
functions.
 Can be used for type-based validation and dynamic behavior in functions.

Conclusion

 Printing types inside functions can aid in debugging, validation, and understanding
the behavior of code.
 Use type() to ensure that the correct data types are being passed and processed.
HIGHER ORDER FUNCTION
 A higher-order function is a function that:

 Accepts one or more functions as arguments.


 Returns a function as a result.

 Allows functions to be passed around as arguments or returned from other functions.

Why Use Higher-Order Functions?

 Flexibility: Functions can be passed as arguments to customize behavior.


 Reusability: Create generic functions that work with any function passed to them.
 Abstraction: Simplify code by abstracting common operations into reusable
functions.

Syntax of a Higher-Order Function

 A higher-order function typically looks like this

: Example 1: Passing Functions as Arguments

# Example functions

# Using higher-order function

print(apply_function(square, 4)) Output:# 16

print(apply_function(double, 4)) Output:# 8

Explanation of Example

 apply_function() is a higher-order function.


 It takes a function (func) and a value (value) as arguments, then applies func to
value.
 Functions like square and double are passed as arguments.

Example 2: Returning Functions from Functions


# Create functions that multiply by 2 and 3

multiply_by_2 = multiplier(2)

multiply_by_3 = multiplier(3)

# Using the returned functions

Explanation of Example 2

 The function multiplier() returns a function that multiplies its input by a given
factor.
 multiply_by_2 and multiply_by_3 are created by passing 2 and 3 to
multiplier().
 These returned functions are then used to multiply numbers.

Key Points

 Higher-order functions can accept or return other functions.


 They provide flexibility, reusability, and abstraction.
 Common in functional programming, decorators, and callback mechanisms.
FUNCTION AS A CALLBACK
 A callback function is a function that is passed as an argument to another function.
 The callback function is called (or "invoked") inside the other function to complete some
task or operation.

How Does a Callback Work?

 Steps:
1. A function accepts another function as an argument.
2. The callback function is executed at an appropriate point inside the main
function.
3. The main function can use the result of the callback to continue processing.

Syntax of a Callback Function

 A function accepts another function as a parameter and calls it

Example 1: Basic Callback Function

Output: #Hello, Alice!

Explanation of Example

 greet(name): A function that prints a greeting.


 execute_callback(callback): Accepts a callback function and calls it with an
argument.
 The greet() function is passed as a callback to execute_callback().

Example 2: Callback with Asynchronous Behavior

Output (after 2 seconds): # Message: Executed after delay


Explanation of Example 2

 delayed_execution() takes a callback function and a delay.


 After waiting for the specified time (simulated with time.sleep()), it calls the
print_message() function as a callback.

Key Points

 Callback functions provide flexibility and modularity in your code.


 They are commonly used in event-driven and asynchronous programming.
 Callbacks allow customizing function behavior without changing the main logic.
FUNCTION USING CLASURES
 A closure occurs when a nested function remembers and can access variables from its
enclosing function, even after the outer function has finished execution.
 Closures allow functions to maintain state between calls without using global variables.
A closure is created when:

1. A function is defined inside another function.


2. The inner function references variables from the outer function.
3. The outer function returns the inner function.

Syntax of Closures

Example 1: Basic Closure

Output: #15

Explanation:

 outer_function(5) returns inner_function, which remembers the


outer_variable value (5).
 closure_function(10) adds the outer_variable (5) and inner_variable (10),
resulting in 15.

How Closures Work (Step-by-Step)

1. outer_function(5) is called, returning the inner_function.


2. closure_function(10) is called:
o It has access to the outer_variable value (5) from the outer scope.
o It uses that value and the argument passed (10) to return the result (15)

Example 2: Function with Persistent State


Explanation:

 counter() returns increment(), which remembers the count variable across calls.
 Each time count_up() is called, the count value is updated and returned, maintaining
its state.

Key Points About Closures

 State Preservation: Closures allow inner functions to "remember" and maintain state
from the outer function.
 Encapsulation: Closures hide state from the outside world while still providing
access to it.
 Memory Efficiency: No need for global variables to preserve state between function
calls.
FUNCTION WITH YIELD (GENERATOR
FUNCTION)
 A generator function is a function that returns an iterator using the yield keyword.
 Unlike regular functions that return a single value and exit, generator functions yield
values one at a time and pause execution between each yield.
 This allows for lazy evaluation (only generating values when needed), making them
memory efficient.

Syntax of a Generator Function

 A generator function uses yield instead of return to produce values:

def generator_function():

yield value

How Does a Generator Work?

 The yield statement pauses the function and sends a value to the caller.
 The function's state is saved and can be resumed when next() is called again.
 This continues until the function exits, or a StopIteration exception is raised.

Example 1: Basic Generator

Output:

5
Explanation of Example

 count_up_to(5) is a generator that yields numbers from 1 to 5.


 The for loop calls next() on the generator until it completes.

Generator with next()

Explanation of Example 2

 square_numbers() is a generator that yields the square of numbers.


 next(squares) is used to retrieve each yielded value.

Key Benefits of Generators

 Memory Efficiency: Generators yield items one at a time instead of storing all values
in memory.
 Lazy Evaluation: Values are computed only when requested (i.e., on-demand).
FUNCTION WITH FOR POSITIONAL
ONLY PAREMETER(PYTHON 3.8+)
 Positional-only parameters are function arguments that must be passed by position, not
by keyword.
 Introduced in Python 3.8 using the / syntax in function definitions.

 These parameters cannot be named when the function is called

Syntax for Positional-Only Parameters

 The / character in a function's parameter list indicates that the parameters before it are
positional-only.

How to Use Positional-Only Parameters

 Parameters before the / must be passed positional

Example 1: Simple Positional-Only Function

Explanation:

 The function multiply accepts x and y only as positional arguments.


 Passing x and y as keyword arguments would raise an error.

Example 2: Combining Positional-Only with Other Parameters


Explanation:

 a and b must be passed positionally.


 c can be passed either positionally or as a keyword argument.

Why Use Positional-Only Parameters?

 Clarifies intent: Some parameters are intended only to be used in a positional manner (e.g.,
for API consistency).
 Prevents misuse: Disallows calling parameters as keywords when they shouldn’t be.
 Improves performance: Avoids ambiguity in performance-critical or low-level functions.

Key Points

 Positional-only parameters are specified using /.


 These parameters can only be passed by position, not by keyword.

You might also like