0% found this document useful (0 votes)
11 views

Functions-UDF-2

Uploaded by

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

Functions-UDF-2

Uploaded by

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

Working with Functions

Bharat Bhushan Mehta


An Introduction
• A Function is a subprogram that acts on data
and often returns a value upon its call.
• It is a collection of statements which is written to
perform a specific task.
• To Execute function we have to call it in the
program.
• Once written a function can also be used in other
programs as library functions.
• There are three types of functions –
1. Built-in (Pre defined / readymade)
2. Modules
3. User Defined Function (UDF)
FEATURES
• Organized Block of statement(s)
• Code Reusability
• Better modularity of program
• Handling program in a easier way
• Reducing Program size
• Makes program more readable & understandable
• Good management of a program
• Can be invoked from another program
• Space saving
• Enhance performance of the program
UNDERSTANDING FUNCTIONS
• To understand what a function is? Let’s see this.
• As in Maths with Polynomials, it is
2x2
for x =1, it will give result as 2 x 12 = 2
for x =2, it will give result as 2 x 22 = 8
for x =3, it will give result as 2 x 32 = 18
it can be represented as –
f(x) = 2x2
then in the above equation –
function Name =f
Argument =x
• Upon passing different argument like 1, 2, 3 etc in function it
returns different values.
RULES TO DEFINE A FUNCTIONS
• One can define functions to provide the required
functionality. Here are simple rules to define a function in
Python.
• Function blocks begin with the keyword def followed by the
function_name and parentheses ( ) .
• Any input parameters or arguments should be placed within
these parentheses. You can also define parameters inside
these parentheses.
• The code block within every function starts with a colon (:)
and is indented.
• The first statement of a function can be an optional
statement – the documentation string of the function
or docstring or Body-of-the-function.
• The statement return [expression] exits a function,
optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
ANATOMY OF A FUNCTIONS
• Syntax of Definition –
def <function_name> ( [List-of-parameter] ) :
body-of-the-function
return [expression]
• Syntax of Call/Invoke/Run a Function –
<function_name> ( [value-to-be-passed-to-argument] )
• Example –
# Function definition is here
def printme ( str ):
"This prints a passed string into this function"
print str
return
# Now you can call printme function
printme ("I'm first call to user defined function!")
printme("Again second call to the same function")
ANATOMY OF A FUNCTIONS
Function_Name Argument

def UDF_Call ( str ):


print(“Passed value is : ")
Function- print (str)
Body Passed value is :
return
return-stmt
Value passed to UDF

Call statement –
# Now you can call printme function
UDF_Call (“Value passed to UDF")
UDF_Call("Again second call to the same function")
UDF

SIMPLE PROGRAM
INPUT

PROCESS

OUTPUT
def sum( a,b): def sum( a,b):
c=a+b c=a+b
print(“Sum = ") return (c)
print (c)

# Now you can call printme function # Now you can call printme function
a=int(input(“Enter 1st number”)) a=int(input(“Enter 1st number”))
b=int(input(“Enter 2st number”)) b=int(input(“Enter 2st number”))
sum(a,b) ans=sum(a,b)
print(“Sum = ")
print(ans)
def Calc_Avg( Total, Strength) :
avg=Total/Strength
return (avg)

# Now you can call UDF function


clas=input(“Enter class : “)
a=float(input(“Enter Total Marks of class”))
b=int(input(“Enter strength”))
ans=Calc_Avg(a, b)
print(“Class Average of class - “,clas, “ = “, ans)
STRUCTURE OF A FUNCTIONS
Top Level Statement –
• Generally all function definition are given at the top
followed by statement which are not part of any
functions.
• Theses statements are not indented at all. These are
called Top Level statement which are not indented.
• Python interpreter starts the execution of a program
from Top Level. This Top Level statements are the part
of main program. Internally Python gives a special
name to top level statements as __main__.
TYPES

FUNCTION
Built-in Functions
• Readymade Solution.
• In python Built-in functions are predefined, we
have to just call them to use.
• These make Python programming efficient and
provide a structure to language.
• Python supports various built-in functions,
which makes programming easy, fast and
efficient.
• These always reside in standard library and we
need not to import any module to use them.
Built-in Functions
1. Type Conversion Functions: Type Conversion
Functions are used to converts the values from one type to
another-
1. int( ) – To convert the string into integer.
2. float( ) – To covert string into float.
3. str( ) – To covert any value into string.

2. Input Functions: This function is used to take input from


user in the form of string.
e.g. name=input( “Enter your name – “)
3. eval function: This function is used to evaluate the value of a
string.
e.g. num=eval(“15+5“)
print(num) # answer will be 20
Built-in Functions
4. min Function : This function returns the smallest value among
given list of values.
min(4, 15, 7, –5)
–5
5. max Function : This function returns biggest value among given
the list of values.
max(4, 15, 7, –5)
15
6. abs Function : This function returns the absolute value of any
integer which is always positive.
abs(–15)
15
abs(15)
15
Built-in Functions
7. type Function : This function is used to identify the type of
any value or variable.
type(15)
<class „int‟>
8. len Function : This function returns the length of given
string.
nm = “Bharat”
6
9. round Function: This function returns the rounded number
of given number up to given position.
round(15.1256, 2)
15.13
round(15.1244, 3)
15.124
Built-in Functions
10. range Function : If you want the series between two
numbers then you can use this function. This is good tool for
FOR Loop. Its syntax is -
range(start, stop, step)

This gives the series from START to STOP – 1 and the interval
between two numbers of series will be STEP.
e.g.
list(range(1,5))
[1, 2, 3, 4]
for i in range(1,10) :
print(i)
PYTHON MODULES
• Module is a .py file which contains the
definitions of functions and variables.
• Module is a simple python file.
• When we divide a program into modules then
each module contains functions and variables.
And each functions is made for a special task.
• Once written code in modules can be used in
other programs.
• When we make such functions which may be
used in other programs also then we write them
in module.
• We can import those module in any program an
we can use the functions.
PYTHON MODULES
• Python provides two ways to import a
module –
• import statement : to import full module.
import math
n = 16
print(math.sqrt(a))
• from : To import all or selected functions from
the module.
from math import sqrt
n = 16
print(math.sqrt(a))
PYTHON MODULES
• In last slide’s example first the math.py file is
searched.
import math
n = 16
print(math.sqrt(a))

• Then a space is created where all the variables and


functions of the math module may be stored.
• Then statements of modules are executed.
MATH MODULES
• Following are the functions
contained in math module –
– ceil(x) returns integer bigger than x or x integer.
– floor(x) returns integer smaller than x or x integer.
– pow(x, n) returns xn.
– sqrt(x) returns square root of x.
– log10(x) returns logarithm of x with base-10
– cos(x) returns cosine of x in radians.
– sin(x) returns sine of x in radians.
– tan(x) returns tangent of x in radians.
help( ) MODULES
• If you forgot that how a library function works then
help( ) is very useful for this situation.
• If this function is used with any module then it
provides the information and details of the given
module and its all the contents.
string Module
• We have already studied about string module in class XI. Here
are some other functions of string module.
– String.capitalize() Converts first character to Capital Letter
– String.find() Returns the Lowest Index of Substring
– String.index() Returns Index of Substring
– String.isalnum() Checks Alphanumeric Character
– String.isalpha() Checks if All Characters are Alphabets
– String.isdigit() Checks Digit Characters
– String.islower() Checks if all Alphabets in a String, are Lowercase
– String.isupper() returns if all characters are uppercase characters
– String.join() Returns a Concatenated String
– String.lower() returns lowercased string
– String.upper()returns uppercased string
– len()Returns Length of an Object
– ord()returns Unicode code point for Unicode character
– reversed()returns reversed iterator of a sequence
– slice()creates a slice object specified by range()
random Module
• When we require such numbers which are not known
earlier
e.g. captcha or any type of serial numbers then in this
situation we need random numbers. And here random module
helps us. This contains following functions-
• randrange (): This method always returns any integer between given
lower and upper limit to this method. default lower value is zero (0) and
upper value is one(1).

• random (): This generates floating value between 0 and 1. it does not
require any argument.
random Module
• randint (): This method takes 2 parameters a,b in which first one is lower
and second is upper limit. This may return any number between these two
numbers including both limits. This method is very useful for randon
selection type of guessing applications.

• uniform (): This method return any floating-point number between two
given numbers.
random Module
• choice (): this method is used for random selection from list, tuple or
string.

• shuffle (): this method can shuffle or swap the items of a given
list.
User-defined Functions
• These are the functions which are made by
user as per the requirement of the user.
• Function is a kind of collection of statements
which are written for a specific task.
• We can use them in any part of our program
by calling them.
• def keyword is used to make user defined
functions.
User-defined Functions
• We use following syntax with def keyword to
prepare a user defined function.

def Function_Name(List_Of_Parameters):
”””docstring”””
statement(s)
After the line containing def
there should be a 4 spaces
Keyword indentation, which is also
know as the body or block
of the function. Function
Definition
User-defined Functions without argument and
without return

Function
Definition

Function Call
User-defined Functions with argument and
without return

In the case of arguments,


the values are passed in
the function’s parenthesis.
And they are declared in
definition as well.
User-defined Functions with argument and
with return

In the case of returning


value, the calculated value
is sent outside the function
by a returning statement.
This returned value will be
hold by a variable used in
calling statement.
User-defined Functions with argument and
multiple return values

In pytho a function
mayn retur multiple
values.n In multiple
returning it returns a
sequence of values to
the calling statement.
These returned values
may be used as per
the requirement.
User-defined Functions with argument and
with return values

Last program may also


be written as follows.

Result will be the tuple


here.
Parameters and Arguments in Functions
• When we write header of any function then the
one or more values given to its parenthesis ( )
are known as parameter.
• These are the values which are used by the
function for any specific task.
• While argument is the value passed at the time of
calling a function.
• In other words the arguments are used to invoke
a function.
• Formal parameters are said to be parameters
and actual parameters are said to be arguments.
Parameters and Arguments in Functions

These are the parameters


.

These are the arguments


.
Types of Arguments
• Python supports 4 types of arguments-
1. Positional Arguments (Required Argument)
2. Default Arguments
3. Keyword (Named Argument) Arguments
4. Variable Length Arguments
Positional Arguments
• These are the arguments which are passed
in correct positional order in function.
• If we change the position of the arguments
then the answer will be changed.
Default Arguments
• These are the arguments through which we can provide
default values to the function.
• If we don’t pass any value to the function then it
will take a pre defined value.
• Its position should be extreme right in the list of parameters.

This is point to remember


that the default argument
should be given after non
default argument.
Keywords Arguments
• If a function have many arguments and we want to change
the sequence of them then we have to use keyword
arguments.
• Biggest benefit of keyword argument is that we need not to
remember the position of the argument.
• For this whenever we pass the values to the function then we
pass the values with the argument name. e.g.

If we use one argument


with keyword then others
must also be called with
keywords otherwise an
error will be raised.
Variable Length Arguments
• As we can assume by the name that we can pass any number of
arguments according to the requirement. Such arguments are
known as Variable Length A rguments.
• We use (*) asterik to give Variable length argument.

You can notice here


that every time the
number of arguments
are different and the
answer is calculated
for each number of
arguments.
Composition Argument in Function Call
• Composition in general refers to using an expression as
part of a larger expression or a statement as a part of
larger statement. In functions’ context, we can
understand composition as follows:
• An arithmetic expression e.g.
sum ( 16+4 )
• A logical expression e.g.
larger( num1 or num2 )
• A function call (function composition) e.g.
int(str(65))
int(float(“7/2”) * 4)
int(str(52)+str(10))
• The above examples show composition of function calls
• A function call as part of larger function call.
Passing ARRAYS /LISTS to Function
• In python we use list as array. Well we have to import numpy
module to use array in python.
• We will pass here list to the function. As we know that list is
better than array.
Scope of Variable
• Scope of variable means the part of program where
the variable will be visible. It means where we can
use this variable.
• We can say that scope is the collection of variables
and their values.
• Scope can of two types -
• Global (module)
– All those names which are assigned at top level in module
or directly assigned in interpreter.
• Local (function)
– Those variables which are assigned within a loop of
function.
Name Resolution Rule
• Whenever variable is being accessed from within a
program or function, Python follows name resolution
rule :
(i) Local Environment (LEGB) : It checks within its
Local Environment or Local namespace if it has a
variable with the same name. if yes, Python uses
its value otherwise next step follows.
(ii) Enclosing Environment (LEGB) : Python checks
whether there is a variable with the same name, if
yes, Python uses its value, if variable not found in
current environment it repeats this step to higher
level enclosing environments, else moves to next
step.
Name Resolution Rule
(iii) Global Environment (LEGB) : Python
checks whether there is a variable with the
same name, if yes, it’s value will be used else
moves to next step.
(i) Built-in Environment (LEGB) : it checks
whether this environment contains all built-
in variables and functions of Python, if there
is a variable with the same name, if yes,
Python uses its value.
Name Resolution Rule
(i) Built-in Environment (LEGB) : It is the widest scope
among all, it checks whether this environment contains all
built-in variables and functions of Python, if there is a
variable with the same name, if yes, Python uses its value.
name <variable> not defined.

Built-in Namespace 4
Global Namespace 3
Enclosing Namespace 2
Local Namespace 1
Name Resolution Rule
• Case 1 : Variable in Global scope but not in local scope :

Global Namespace 3
n1=4 n2=5

Enclosing Namespace 2
Not any intermediate
enclosing variable

Local Namespace 1
x=4
y=5
s=9
Name Resolution Rule
• Case 2 : Variable neither in local scope nor in
global scope
• If there is a situation in which variable is neither in
its local environment nor in its parent environment?
Then Python will report an error.

Global Namespace 3
Not any Global variable

Local Namespace 1
Not any Local
variable
Name Resolution Rule
• Case 3 : Same variable in both LOCAL & GLOBAL
scope
• If both local and global variables having same
name. Here Local Variable hides the Global
Variable if control is in local environment.

Global Namespace 3
n = 10

Local Namespace
n=5
Name Resolution Rule
• What if GLOBAL variable is required in LOCAL
environment. Keyword global will be used in this
case.

Global Namespace 3
n = 10

Local Namespace
No Local variable
created
Food for Thought
1. Write a Function CountVowel( ) which takes string as
parameter count and return number of vowels (both
cases) .
2. WAF SumEven( ) which takes List Lst=[1,2,3,5,6,7,4,8]
find sum of all even number and return.
3. WAF Multiple5() which takes List Lst=[2,4,5,7,15,20]
find all multiple of 5 and return.
4. WAF PefSqr( ) which takes List of int as parameter find
sum of all perfect square integers.
5. WAF DiffChars( ) which takes string as parameter, find
number of different characters.
6. WAF Words( ) which takes string as parameter find
and display all words having 3 characters.
Using main() as a Function
• Main function is not necessary in python.
• We can use it by its name as –
Flow of Execution at the Time of Function Call
• The execution of any program starts from the very first line
and this execution goes line by line.
• One statement is executed at a time.
• Function doesn’t change the flow of any program.
• Statements of function doesn’t start executing until it is called.
• When function is called then the control is jumped into the
body of function.
• Then all the statements of the function gets executed from top
to bottom one by one.
• And again the control returns to the place where it was called.
• And in this sequence the python program gets executed.

You might also like