cs ppt class 11 user defined function
cs ppt class 11 user defined function
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:
# 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:
Order of Parameters
Key Rule: *args must appear before
**kwargs.
Example:
# 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 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 functions
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.
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:
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: 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:
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:
# 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):