Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

cs ppt class 11 user defined function

best hand m,ade ppt onnnnnnnnnnnnnnnnn user defined fuction for class 11 with the frequently asked questions and ansers

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)
2 views

cs ppt class 11 user defined function

best hand m,ade ppt onnnnnnnnnnnnnnnnn user defined fuction for class 11 with the frequently asked questions and ansers

Uploaded by

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

PPT ON

USER
DEFINED
FUNCTIO
N
CLASS 11-
A

MADE BY-

KUNJ GOYAL
HIRDYANSH
KAPIL

TANISHQ
BHARTI

INTRODUCTION
What is a Function?
 A function is a block of reusable code that
performs a specific task.
 Functions help break a program into smaller,
modular chunks, making the code more
organized and easier to maintain.
User Defined Functions (UDF):
 In Python, a User Defined Function (UDF) is
a function that you, the programmer, define.
 UDFs allow us to create custom functions to
perform tasks that aren’t covered by built-in
Python functions.
Why Use User Defined Functions?
 Reusability: Once defined, a function can be
used multiple times in a program.
 Modularity: Functions help break large
programs into smaller, manageable parts.
 Clarity: UDFs make the code more readable
and organized.

TYPES OF FUNCTION

1. SIMPLE FUNCTIONS
2. (ARGUMENTS)ONLY
PARAMETER
3. MULTIPLE PARAMETER
4. DEFAULT ARGUMENTS
5. (ARGS)ARBITATRY NO. OF
ARGUMENTS
6. (KWARGS) ARBITATRY NO. OF
ARGUMENTS
7. RETURNING VALUE FROM A
FUNCTIONS
8. (ANONYMOUS FUNCTIONS)
LAMBADA FUNCTIONS
9. NESTED FUNCTIONS
10. (ARGS AND KARGAS)
ARBITATRY NO. OF ARGUMENTS
11. FUNCTIONS WITH TYPE
PRINTING
12. HIGHER ORDER FUNCTIONS
13. FUNCTION AS A CALLBACK
14. (PHTHON 3.8+) FUNCTIONS
WITH FOR POSITIONAL ONLY
PARAMETER

SIMPLE FUNCTIONS
 A function in Python is a block of code that only
runs when it is called.
Functions can take inputs (arguments) and return
outputs (results).
 Syntax to define a function:

Example 1: A function to add two


numbers

# Output: 8
Explanation:
 add_numbers is the function name.
 a and b are parameters.
 The function returns the sum of a and b.
Combining Simple and Default
Functions
Example
Explanation:
 The b parameter has a default value of 5.
 If b is not provided, it defaults to 5; otherwise,
it uses the value passed as an argument.
(ARGUMENT) ONLY
PARAMETER
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.

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
PARAMETER
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.

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.

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.

FREQUENTLY ASKED
QUESTIONS
1. What is a function in Python?
2. Write a Python function that
takes two arguments: a name and
an age. Set the default value of
age to 18. Call the function with
and without the age argument.
3. How can we pass multiple
arguments to a Python function?
Give an example.
4. Write a Python function that
takes three parameters: a, b, and
c. Set default values for b and c,
and add all three parameters
inside the function.

(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.

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():
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.
FREQUENTLY
ASKED QUESTIONS
1. Can *args and **kwargs be
used together in the same
function?
2. What happens if we pass
both positional and keyword
arguments while using *args
and **kwargs?
3. Can we pass a tuple or a
dictionary to a function using
*args and **kwargs?
4. What is the use of the
return keyword in Python?
5. Can a Python function
return multiple values?

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.
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.

(USING ARGS &


KWARGS
TOGETHER)
FUNCTION WITH
VARIABLE NO. OF
ARGUMENT NESTED
FUNCTION
 *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.
FREQUENTLY ASKED
QUESTIONS
1. Can a nested function return a
function that uses *args and
**kwargs?
2. How do you implement type
printing in Python functions?
3. How do *args and **kwargs
help in nested functions with
variable arguments?
4. What happens if I use *args
and **kwargs in the outer
function but not in the nested
function?
5. What happens if the number of
arguments passed to the inner
function doesn’t match its
definition?
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

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.

(PYTHON 3.8+)
FUNCTION WITH
FOR POSITIONAL
ONLY PARAMETER
 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.
. 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.

FREQUENTLY ASKED
QUESTIONS
1.What is a function as a callback in Python?
2.How do you handle both positional and
keyword arguments in a function?
3.How can I use a function as a callback for
event handling or asynchronous code
ANSWERS OF ALL
THE ABOVE
QUESTIONS
ASKED
1. What is a function in Python?
A function in Python is a block of code that is
designed to perform a specific task. It allows
you to group code into reusable pieces, which
can be called multiple times. Functions in
Python are defined using the def keyword,
followed by the function name and parameters
(optional).
Example:

2. Write a Python function that takes two


arguments: a name and an age. Set the
default value of age to 18. Call the function
with and without the age argument.

Here, age=18 sets the default value for age if


no value is provided when calling the
function.
3. How can we pass multiple arguments to a
Python function? Give an example.
We can pass multiple arguments to a Python
function in several ways:
 Using positional arguments
 Using *args (for variable
positional arguments)
 Using **kwargs (for keyword
arguments)
Example using *args:
# Output: 6
4. Write a Python function that takes three
parameters: a, b, and c. Set default values
for b and c, and add all three parameters
inside the function.

5. Can *args and **kwargs be used


together in the same function?
Yes, you can use both *args and **kwargs
in the same function. The order should be: first
*args (for positional arguments), then
**kwargs (for keyword arguments).
Example:
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name':
'Alice', 'age': 30}
6. What happens if we pass both positional
and keyword arguments while using *args
and **kwargs?
When you pass both positional and keyword
arguments, Python will correctly assign
positional arguments to *args and keyword
arguments to **kwargs. However,
positional arguments must come before
keyword arguments.
Example:

Output:
a=1, b=2, args=(3, 4, 5), c=20,
kwargs={'name': 'John'}
7. Can we pass a tuple or a dictionary to a
function using *args and **kwargs?
Yes, you can pass a tuple using *args and a
dictionary using **kwargs to a function.
Example:

Output:
Args: (1, 2, 3)
Kwargs: {'name': 'Alice',
'age': 30}
8. What is the use of the return keyword in
Python?
The return keyword in Python is used to
exit a function and optionally pass a value
back to the caller. Without return, a
function returns None by default.
Example:

Output: 7
9. Can a Python function return multiple
values?
Yes, a Python function can return multiple
values, typically as a tuple. You can return
multiple values separated by commas.
Example:

Output: (15, 5, 50)


10. Can a nested function return a function
that uses *args and **kwargs?
Yes, a nested function can return a function
that uses *args and **kwargs.
Example:

# Output: 36
11. How do you implement type printing in
Python functions?
You can use the type() function to print the
type of a variable or parameter inside a
function.
Example:

12. How do *args and **kwargs help in


nested functions with variable arguments?
*args and **kwargs allow nested
functions to accept a variable number of
arguments, making them flexible.
Example:

Output:
Inner args: (1, 2, 3), Inner
kwargs: {'x': 10, 'y': 20}
13. What happens if I use *args and
**kwargs in the outer function but not in
the nested function?
If you use *args and **kwargs in the outer
function but not in the nested function, the
inner function will not accept those arguments
unless you explicitly pass them when calling
the inner function.
Example:
14. What happens if the number of
arguments passed to the inner function
doesn’t match its definition?
If the number of arguments passed to the inner
function doesn’t match its definition, Python
will raise a TypeError.
Example:

15. What is a function as a callback in


Python?
A callback function is a function that is passed
as an argument to another function and is
expected to be called (or executed) at a later
time. It allows for dynamic function
execution.
Example:

# Output: Result: 10
16. How do you handle both positional and
keyword arguments in a function?
You can handle both positional and keyword
arguments by defining parameters in the
function definition. Use *args for positional
arguments and **kwargs for keyword
arguments.
Example:
17. How can I use a function as a callback
for event handling or asynchronous code?
In event handling or asynchronous
programming, you can pass a function as a
callback that is executed when a certain event
occurs or when a task completes.
Example (Event handling):

These answers should give you a good


understanding of Python functions and their
various features! Let me know if you need
further clarification on any point.
THANK
YOU
EVERYON
E

You might also like