L-4 Functions in Python
L-4 Functions in Python
✓ Functions in Python
✓ Pre-defined Functions
Functions In Python
Built-in Functions
Examples
Overview
Python Functions
Functions In Python
Grouping Related Instructions in a Function
➢ Functions are used to group together a certain number of related instructions
➢ These are reusable blocks of codes written to carry out a specific task
➢ Depending on the task a function is supposed to carry out, it might or might not return a value
Function Description
abs() Returns the absolute value of a number
bin() Returns the binary version of a number
len() Returns the length of an object
list() Returns a list
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
pow() Returns the value of x to the power of y
print() Prints to the standard output device
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
input() Allowing user input
int() Returns an integer number
complex() Returns a complex number
bytes() Returns a bytes object
Python Functions
✓ Find the total number of characters in the string “Python too good!”
Functions In Python
✓ Writing a Function
✓ Type of Functions
✓ Calling Function
✓ Scope & Lifetime of Variables
Argument Passing
➢ While defining a function in Python, we need to follow the below set of rules:
✓ The def keyword is followed by a function-name which is followed by parentheses containing the
arguments passed by the user and a colon at the end.
✓ After adding the colon, the body of the function starts with an indented block in a new line.
✓ The return statement sends a result object back to the caller. A return statement with no argument
is equivalent to return none statement.
➢ Now, there are two ways in which we can call a function, after we have defined it. We can either call it
from another function or we can call it from the Python prompt
✓ Example:
# Defining a function that will print the passed string
#calling a function
printOutput(“Welcome to world of Python”)
Argument Passing In Functions Python Functions
➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:
➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:
➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:
➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:
✓ The following example gives an idea on default arguments, it prints default age if it is not passed
➢ We may need to process a function for more arguments than those specified while defining the
function
➢ These arguments are called variable-length arguments and are not named in the function
definition, unlike regular arguments
✓ Syntax:
def functionname([formal_args,] *var_args_tuple ):
function_suite return [expression]
➢ An asterisk (*) is placed before the variable name that holds the values of all variable number of
arguments
➢ This tuple remains empty if no additional arguments are specified during the function call
Python Functions
Variable Length Argument Passing (Continue)
Any Number of Arguments can be Passed
➢ Following is a simple example:
➢ The scope of a variable is a part of the program where the variable is recognizable
➢ Lifetime of a variable is the time period till when the variable exists in the memory
➢ Variables defined inside the function only exist as long as the function is being executed
➢ So, the lifetime of a variable defined inside a function ends when we return from the function or when
the control comes out of the function
➢ According to their scope, the variables may be defined as: local or global variables
Python Functions
Local Variables & Global Variables
Where is a variable defined & used?
➢ A variable that is declared inside a python function or a module can only be used in that specific
function or Python Module. This kind of variable is known as a local variable
➢ Python interpreter will not recognize that variable outside that specific function or module and will
throw an error if that variable is not declared outside of that function
➢ On the other hand, global variable in Python is a variable that can be used globally anywhere in the
program
➢ It can be used in any function or module, and even outside the functions, without having to re-declare
it
Python Functions
Local Variables & Global Variables (Continue)
Example
# This is global variable total
total = 0
# Function definition is here which adds both the parameters and return sum
sum( 10, 20 )
print ("Outside the function global total : ", total )
Python Functions
Deleting Variables
How to Remove Variables from Memory?
➢ Python provides a feature to delete a variable when it is not in use to free up space
➢ Using the command del ‘variable name’, we can delete any specific variable.
del var1[,var2[,var3[....,varN]]]]
➢ You can delete a single object or multiple objects by using the del statement.
➢ For example:
del var1
del var_2, var_3
Python Functions
✓ Declare a local variable Score and save the calculated factorial value in it
✓ Check if calculated factorial score is <500 then return “Score<500” else return
“Score>500”
➢ Write a function calculation() such that it can accept two variables and calculate the addition
and subtraction of them. And also it must return both addition and subtraction in a single
return call
Python Functions
Lambda Functions
map() function
➢ These functions are called anonymous because they are not declared in the standard manner by
using the def keyword. You can use the lambda keyword to create small anonymous functions
➢ Lambda forms can take any number of arguments but return just one value in the form of an
expression
➢ An anonymous function cannot be a direct call to print because lambda requires an expression
➢ Lambda functions have their own local namespace and cannot access variables other than those
in their parameter list and those in the global namespace
Python Functions
Lambda Functions (Continue)
Anonymous Functions
➢ Syntax: The syntax of lambda functions contains only a single statement, which is as
follows:
➢ The map() function applies a given function to each item of an iterable (list, tuple etc.) and
returns a list of the results.
➢The syntax of map() is:
➢ Parameters :
✓ function : It is a function to which map passes each element of given iterable.
✓ iterable : It is a iterable which is to be mapped.
➢You can pass one or more iterable to the map() function
➢Returns a list of the results after applying the given function to each item of a given iterable
(list, tuple etc.)
➢The returned value from map() (map object) then can be passed to functions like list() (to
create a list), set() (to create a set) .
Python Functions
filter() function in Python
Using filter()
➢ 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
➢The syntax of filter() is:
filter(function, sequence)
➢ Parameters :
✓ function: function that tests if each element of a sequence true or not
✓ sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any
iterators
➢It returns an iterator that is already filtered
Return Statement Python Functions
➢ Through return statement, the control exits a function and may pass a value/expression to the caller. A return
statement with no arguments is the same as return Nothing except control.
✓ Example:
# Function definition adds both the parameters and return them
def sum( arg1, arg2 ):
total = arg1 + arg2
print ("Inside the function : ", total)
return total
➢ Write a Python program to create a lambda function that adds 15 to a given number passed in
as an argument
➢ Create a lambda function that multiplies argument x with argument y and print the result
➢ Write a lambda function to square and cube every number in a given list of integers. Use
map() function also with lambda function
➢ Use filter() to separate a list of vowels from alphabets