functions
functions
Function
• A function is a block of code which only runs when it is
called.
• You can pass data, known as parameters, into a
function.
• A function can return data as a result.
Example
def my_function():
print("Hello from a function")
Defining Functions
Function definition begins with Function name and its
“def.” arguments.
def get_final_answer(filename):
“““Documentation
String””” line1
line2 Colon.
return total_counter
The indentation
matters… First line
with less The keyword ‘return’ indicates
indentation is considered to the value to be sent back to
be outside of the function the caller.
definition.
No header file or declaration of types of function or
arguments
Python and Types
Parameters:
fun: It is a function to which map
passes each element of given
iterable.
Example:
In this example, Python program showcases
the usage of the map function to double
each number in a given list by applying the
double function to each element, and then
printing the result as a list.
Parameters:
fun: It is a function to execute on each element of the
iterable object
iter: It is iterable to be reduced
Example :
In this example, we are using reduce() function from the
functools module to compute the product of elements in a given
list by continuously applying the lambda function that multiplies
two numbers together, resulting in the final product.
import functools
# Define a list of numbers
numbers = [1, 2, 3, 4]
Output
Product of list elements: 24
Filter Function in Python
The filter() method filters the given
sequence with the help of a function that
tests each element in the sequence to be
true or not.
Parameters:
function: function that tests if each
element of a sequence is true or not.
sequence: sequence which needs to be
filtered, it can be sets, lists, tuples, or
containers of any iterators.
Example :
In this example, we defines a function is_even to check whether a
number is even or not. Then, it applies the filter() function to a list of
numbers to extract only the even numbers, resulting in a list containing
only the even elements. Finally, it prints the list of even numbers.
Output
Even numbers: [2, 4, 6, 8, 10]