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

L-4 Functions in Python

Uploaded by

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

L-4 Functions in Python

Uploaded by

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

Python Functions

Function Handling In Python - Built-in Function

✓ Functions in Python
✓ Pre-defined Functions

Trainer: Ms. Nidhi Grover Raheja


Connect on LinkedIn: www.linkedin.com/in/nidhi-grover-raheja-904211138
Python 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

➢ A function might or might not require inputs

➢ Functions are only executed when they are specifically called

➢ Depending on the task a function is supposed to carry out, it might or might not return a value

➢ There are three types of functions, named as:

✓ Pre-defined or Built-in functions


✓ User-Defined functions
✓ Lambda Functions
Python Functions
Some Built-in Functions In Python
Pre-defined Function

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

Exercises: Time for Action

➢ Use Built-In functions in Python to implement the following:

✓ Convert the character ‘A’ in python into it’s ASCII value

✓ Create a complex number from given integer parameters (9,2)

✓ Convert an integer to it’s equivalent binary string

✓ Return absolute value of negative number (-25)

✓ Find the total number of characters in the string “Python too good!”

✓ Take user input of two numbers, sum them and display


Python Functions

Functions In Python

✓ Writing a Function
✓ Type of Functions
✓ Calling Function
✓ Scope & Lifetime of Variables

Trainer: Ms. Nidhi Grover Raheja


Connect on LinkedIn: www.linkedin.com/in/nidhi-grover-raheja-904211138
Python Functions

User Defined Functions

Argument Passing

Scope & Lifetime of variables


Overview
Exercise
Python Functions
User Defined Functions In Python
Creating Own Functions

➢ While defining a function in Python, we need to follow the below set of rules:

✓ The def keyword is used to start the function definition.

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

➢ Syntax for writing a function in Python where a1,a2…aN are arguments:

def function_name(a1, a2, … aN):


return
Python Functions
User Defined Functions In Python (Continue)
How to Write and Call Own Functions
➢ To execute a function, we must call it. Only when it is specifically called, a function will execute and
give the required output

➢ 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

def printOutput( val):


print (val)
return

#calling a function
printOutput(“Welcome to world of Python”)
Argument Passing In Functions Python Functions

How are Parameters Passed in a Function?


➢ All parameters (arguments) in the Python language are passed by reference

➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:

# Function definition is here


def func1( mylist ):
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return

# Now you can call function func1() as follows:


mylist = [10,20,30]
func1( mylist )
print ("Values outside the function: ", mylist)
Argument Passing In Functions Python Functions

How are Parameters Passed in a Function?


➢ All parameters (arguments) in the Python language are passed by reference

➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:

# Function definition is here


def func1( mylist ):
print ("Values inside the function before change: ", mylist) This will print mylist [10, 20, 30]
mylist[2]=50
print ("Values inside the function after change: ", mylist) This will print mylist [10, 20, 50]
return

# Now you can call function func1() as follows:


mylist = [10,20,30]
func1( mylist )
print ("Values outside the function: ", mylist) This will also print mylist [10, 20, 50]
Argument Passing In Functions Python Functions

How are Parameters Passed in a Function?


➢ All parameters (arguments) in the Python language are passed by reference

➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:

# Function definition is here


def func1( mylist ):
print ("Values inside the function before change: ", mylist) This will print mylist [10, 20, 30]
mylist[2]=50
print ("Values inside the function after change: ", mylist) This will print mylist [10, 20, 50]
return

# Now you can call function func1() as follows: WHY??


mylist = [10,20,30]
func1( mylist )
print ("Values outside the function: ", mylist) This will also print mylist [10, 20, 50]
Argument Passing In Functions Python Functions

How are Parameters Passed in a Function?


➢ All parameters (arguments) in the Python language are passed by reference

➢ It means if you change what a parameter refers to within a function, the change also reflects back in the calling function
✓ For example:

# Function definition is here


def func1( mylist ):
print ("Values inside the function before change: ", mylist) This will print mylist [10, 20, 30]
mylist[2]=50
print ("Values inside the function after change: ", mylist) This will print mylist [10, 20, 50]
return
This is because argument mylist
# Now you can call function func1() as follows: is passed by reference and
mylist = [10,20,30] changes are reflected
func1( mylist )
print ("Values outside the function: ", mylist) This will also print mylist [10, 20, 50]
Default Argument Passing In Functions Python Functions

Default Arguments with Predefined Values


➢ A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

✓ The following example gives an idea on default arguments, it prints default age if it is not passed

# Function definition is here


def func2( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call func2() function

func2( age = 50, name = “riya" )


func2( name = “suman” )
Python Functions
Variable Length Argument Passing In Functions
Any Number of Arguments can be 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:

# Function definition is here

def func1( arg1, *vartuple ):


print ("Output is: ")
print (arg1)

for var in vartuple:


print (var)
return

# Now you can call func1 function


func1( 10 )
func1( 70, 60, 50 )
Python Functions
Scope & Lifetime Of Variables
Where is a variable alive & visible?

➢ 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

def sum( arg1, arg2 ): # Here total is local variable.


total = arg1 + arg2;
print ("Inside the function local total : ", total)
return total

# Now you can call sum function

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.

➢ The syntax of the del statement is −

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

Exercises: Time for Action

➢ Create a function calc_factorial(num) to calculate factorial of number in parameter

✓ Call the function for each of these numbers as parameter: 5,7,9

✓ 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

Functions In Python: Lambda Functions

✓ Writing a Lambda Function


✓ map()
✓ filter()

Trainer: Ms. Nidhi Grover Raheja


Connect on LinkedIn: www.linkedin.com/in/nidhi-grover-raheja-904211138
Python Functions

Lambda Functions

map() function

Filter() function Overview


Exercises
Python Functions
Lambda Functions
Anonymous Functions

➢ 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

➢ They cannot contain commands or multiple expressions

➢ 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:

lambda [arg1 [,arg2,.....argn]]:expression

✓ Example: Following is an example to show how lambda form of function works −

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2

# Now you can call sum as a function


print ("Value of total : ", sum( 7, 4 ))
print ("Value of total : ", sum( 10, 20 ))
Python Functions
map() function in Python
Using map()

➢ 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:

map(function, iterable, ...)

➢ 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

Return Data and/or Control


➢ The statement used to return value and/or control is:
return [expression]

➢ 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

# Now we can call sum function


total = sum(10, 20)
Python Functions

Exercises: Time for Action

➢ 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

You might also like