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

CH 3 Function

The document discusses functions in Python programming. It explains what functions are, different types of functions including built-in, module, and user-defined functions. It also covers advantages of using functions, parameters and arguments in functions, and different types of arguments like positional, default, keyword, and variable length arguments.

Uploaded by

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

CH 3 Function

The document discusses functions in Python programming. It explains what functions are, different types of functions including built-in, module, and user-defined functions. It also covers advantages of using functions, parameters and arguments in functions, and different types of arguments like positional, default, keyword, and variable length arguments.

Uploaded by

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

Unit-I: Programming and Computational Thinking-2 Visit: https://dineshkvs.wordpress.

com

CHAPTER – 3: WORKING WITH FUNCTION


What is Functions:
A function is a programming block of codes which is used
to perform a single, related task. It only runs when it is
called. We can pass data, known as parameters, into a
function. A function can return data as a result.
Large programs are often difficult to manage, thus large
programs are divided into smaller units known as
functions.
Types of Function: Functions in python is of mainly three
types:

Function

1. Built in Function 2. Module 3. User Define Function

Advantages of Using functions:


1.Program development made easy and fast : Work can
be divided among project members thus implementation
can be completed fast.
2.Program testing becomes easy : Easy to locate and
isolate a faulty function for further investigation
3.Code sharing becomes possible : A function may be
used later by many other programs this means that a
python programmer can use function written by others,
instead of starting over from scratch.
4.Code re-usability increases : A function can be used to
keep away from rewriting the same block of codes which
we are going use two or more locations in a program. This
is especially useful if the code involved is long or
complicated.
Unit-I: Programming and Computational Thinking-2 Visit: https://dineshkvs.wordpress.com

5.Increases program readability : The length of the


source program can be reduced by using/calling functions
at appropriate places so program become more readable.
Built – in Functions:- These are the predefined functions
that are already available in standard library of Python
and provides efficiency and structure to Python and no
need to import it.
Examples:-
Type conversion functions:- int ( ) , str ( ) , float ( ) , input
(), eval( ) , min (), max ( ), abs ( ),type ( ) , len ( ), round ( ),
range()
Modules :- As the programme become more lengthy and
complex, there arises a need for the tasks to be split into
smaller segments called modules.
A module is a file containing functions and variables
defined in separate file.
There are commonly used modules in Python that are
used for certain predefined tasks and they are called
libraries.
Importing modules in Python:-
Python provides to important methods to import modules
in a program.
i) Import statement
ii) From
Synyax:- import modulename1, modulename2,………….
Example:- import math , import pandas as pd
To access any of the functions present in the imported
module, specify the name of the module followed by name
of the function, separated by dot(.)
Example: Result = math . sqrt (64)
i)ceil(x);- Returns the smallest integer that is greater than
or equal to x.
math . ceil(3.4) → 4
ii)floor(x) :- Returns the largest integer that is less than
or equal to x.
math.floor (100.72) → 100.0
iii)pow(x,y):- Returns value of xy.
math.pow(2,4) → 16.0
iv)fabs() :- Returns absolute(Positive value) of the
number.
math . fabs(-15) → 15.0
import ramdom :- The various functions associated with
this module.
i)randrange( ) :- It generates an integer between its lower
(default 0) and upper ( default 1 ) argument.
random . randrange (30); Generates number from 0 to
29.
ii)random( ) :- it generates number between 0 to 1.
iii)randint(x,y):- Returns the number N in the inclusive
range x,y such that x<= N<= y.
random.randint(0,9) → 7
iv)uniform ( ) :- It return a random floating point number
N between x and y such that x<=N < y.
random . uniform ( 1,100) → 46.7865
v)choice ( ) :- It is used for random selection from a
sequence like a list , tuple,or string.
D = random.choice ( [‘East’, ‘West’, ‘North’ , ‘South’ ])
print(D) → North
Unit-I: Programming and Computational Thinking-2 Visit: https://dineshkvs.wordpress.com

vi)shuffle ( ) :- It is used to swap the contents of a list i.e.


generate a random permutation of a list in-place.
Syntax:- shuffle(list)
Fruits = [ ‘Apple’ , ‘Orange’, ‘Banana’ , ‘Apricot’, ‘Graps’ ]
random.shuffle (Fruits)
print(Fruits)
Reshuffled Fruits; [ ‘Apple’ , ‘Banana’ , ‘Apricot’, ‘Graps’,
‘Orange’ ]
Q. What will be the output of following code:

b. YELLOW* c. WHITE*WHITE* d. YELLOW*


a. RED* YELLOW*YELLOW*
WHITE* WHITE*WHITE*
WHITE* BLACK* BLACK*
BLACK* BLACK* BLACK* BLACK*
RED*RED*
BLACK*
RED* RED* RED* RED* RED* RED*
RED*

User Defined functions(UDF):-


A function is a set of statements that performs
a specific task a common structuring elements that allows
you to use a piece of code repeatedly in different part of
program. Functions are also known as sub-routine
methods, procedure or subprogram.

Syntax to create USER DEFINED FUNCTION:-


def function_name([comma separated list of
parameters]) :
Statement –1
Statement –2 FUNCTION
DEFINITION
KEYWORD
S Statement –3
-
-
-
Statement -n
Pointes to remember:-
Keyword def marks the start of function header
Function name must be unique and follows naming rules
same as for identifiers
Function can take arguments. It isoptional
A colon(:) to mark the end of function header
Function can contains one or more statement to perform specific
task
An optional return statement to return a value
from the function.
Function must be called/invoked to execute its
code

User Defined Functions can be :-


1. Function with no arguments and no return
2. Function with arguments but no return value
3. Function with arguments and return value
4. Function with no argument but return
value
Let us understand each of the function type with
example.
1.Function with no arguments and no return:-
This type of function is also known as void
function.

Function
Definition

Function Call Statement

OUTPUT

2.Function with arguments but no return value:-


➢ Parameters are given in the parenthesis separated by
comma.
➢ Values are passed for the parameter at the time function
calling.
Example 1:

Function Definition

Function Call Statement

OUTPUT
Unit-I: Programming and Computational Thinking-2 Visit: https://dineshkvs.wordpress.com
Example 2:

3.Function with arguments and return value:-


We can return values from function using return keyword and
it always returns the result at function call statement.
The return value must be used at the calling place
by –
➢ Either store it any variable
➢ Use with print()
➢ Use in any expression
Note: The return statement ends a function execution
even if it is in the middle of the function. Anything
written after the return statement, will become
unreachable code.
4.Function with no argument but return value:-
Function may or may not return a value. Non
returning function is also know as VOID function. It
may or may not contain return. If it contain return
statement then It will be in the form of: return
Unit-I: Programming and Computational Thinking-2 Visit: https://dineshkvs.wordpress.com

PARAMETERS AND ARGUMENTS IN FUNCTION


➢ Parameters are the value(s) provided in the parenthesis when we write
function header. These are the values required by function to work.
➢ If there are more than one parameter, it must be separated by comma(,)
➢ An Argument is a value that is passed to the function when it is called. In
other words arguments are the value(s) provided in function
call/invoke statement
➢ Parameter is also known as FORMAL ARGUMENTS/PARAMETERS
➢ Arguments is also known as ACTUAL ARGUMENTS/PARAMETER
➢ Note: Function can alter only MUTABLE TYPE values.

Example of Actual / Formal Arguments:

Formal Arguments

Actual Arguments

Types of Arguments:-
There are 4 types of Actual Arguments allowed in Python:
1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments
1.Positional arguments:- These are the arguments passed to afunctionin
correct positional order.

Here the Value of A and B passed to the Variable x and y respectively i.e. in the
order of their position.
Note: If the number of Actual and Formal arguments are differ, than Python
gives an error.
2.Default Arguments:-
➢ Some times we can provide default values for our positional arguments. In
this case if we are not passing any value then default values will be
considered.
➢ Default argument must not followed by non-default arguments i.e.
the argument appears at the left side of the default argument must
have the default value.
def Interest (principle = 5000, Rate = 10.0 , Time = 3) :
def Interest (principle, Rate = 10.0 , Time = 3) : Valid
def Interest (principle, Rate , Time = 3) :
def Interest (principle = 6000, Rate = 10.0 , Time) :
Invalid
Example:
Note: Default arguments are also used the theory of positional arguments.

3.Keyword arguments:-
➢ The default keyword gives flexibility to specify default value for a
parameter so that it can be skipped in the function call,if need.However,still
we cannot change the order of arguments in function call i.e. you have to
remember the order of the arguments and pass the value accordingly.

➢ To get control and flexibility over the values sent as arguments,python offers
KEYWORD ARGUMENTS.

➢ This allows to call function with arguments in any order using name of the
arguments.

Example:

Change the order of


Arguments

4.Variable length arguments:- In some situations , we can pass variable


number of arguments to a function. These arguments are called Variable Length
Arguments/Parameters.
➢ Variable Length Arguments/Parameters are declared with * (Asterisk)
symbol in Python like def F1(*N) :
➢ We can call this function by passing any number of arguments , including
zero. Internally, all these variable are represented in the form of Tuple.

Example:
Rules for Combining All Four types of Arguments:
An argument list must first contain positional arguments followed by keyword
arguments.
Keyword arguments should be taken from the required arguments.
Youcannot specify avalue for an argument more than once.

Examples of Legal / Illegal Function Call:


def Average ( N1 , N2 , N3 = 20) :
return (N1+N2+N3)/3.0
Function Call Legal/Illegal Reason
Average(N1=10,N2=20,N3=30) Legal Non default values provided as named
arguments
Average(N3=10,N1=20,N2=30) Legal Keyword argument can be in any
order
Average(10,N2=20,N3=30) Legal Positional argument before the keyword
arguments
Average(N3=10,N1=20,30) Illegal Keyword argument before the
positional arguments
Average(10,N1=20,N2=30) Illegal Multiple values provided for N1
Average(10,NUM2=20,N3=30) Illegal Undefined Argument NUM2
Average(10,N3=30) Illegal A required argument N2 is missing

Returning Multiple Values:- A function in Python can return multiple


values.
Example 1:

Example 2:

Note:- The multiple values returned by return statement in the form of tuple.

Example:-

Result is in the form of TUPLE

COMPOSITION
It refers to using an expression as a part oflarge expression, or a statement as a
part of large statement.
Example:
Max ((a+b),(b+c)) # ARITHMATIC
Prize(Cash or Card) #LOGICAL
NAME = “Vikram”
Print(NAME.replace(“m”, “nt”).upper()) # FUNCTION

Passing LISTs/Array to Function:-


LIST:- Arrays in Python are actually a LIST which contain mixed data types.
But LISTs are better than arrays as LISTs hold elements of different data type
, Array holds elements of same data types.
Example:

SCOPE OF VARIABLES
➢ All variables in a program may not be accessible at all locations in that
program. It depends upon their declaration place inside the program.
➢ Scope of the variables refers to the part of the program where it is visible
i.e. area where you can use.
➢ There are two types of Scope of variables:-

a) Global:-
➢ variables declared at the top of the program or declared global in a
function.
➢ Variable defined outside all functions are global variables .
b)Local:-
➢ Variables declared inside a function definition or loop.
➢ A name declare in a function body is said to have local scope i.e. it can be used
only within this function and the other block inside the function.
➢ The formal parameters are also having local scope.

Example- Local and Global Scope

‘a’ can’t access


because it is local to
function area

Example - 2

The variable ‘ar’ is


accessible in the function
showarea() because it is
Note:- The Global variable used in the function must be declared as “global vari
able name” i.e. global count , otherwise an error occurred like
“local variable 'count' referenced before assignment”
LIFE TIME OF A VARIABLE
Global variables lives in memory as long as the program run i.e. its life time is
as long as the program run.
Local variables lives in memory as long as the functions where it is declared
run .i.e. functions over then Local variables removed from the memory.

Name Resolution( Scope Resolution):


For every name used within program python follows name resolution rules known as
LEGB rule.
(i) LOCAL : first check whether name is in local environment, if yes Python uses
its value otherwise moves to (ii)
(ii) ENCLOSING ENVIRONMENT: if not in local, Python checks whether name is
in Enclosing Environment, if yes Python uses its value otherwise moves to (iii)
(iii)GLOBAL ENVIRONMENT: if not in above scope Python checks it in Global
environment, if yes Python uses it otherwise moves to (iv)
(iv)BUILT-IN ENVIRONMENT: if not in above scope, Python checks it in built-in
environment, if yes, Python uses its value otherwisePython would report the error:

name <variable> not defined


Find output of the given program:
Program with variable both Local and Global Scope:-

Using Global variable “value” in Local Scope:-


Variable “val” neither Global nor Local Scope:-

Variable in Global not in Local (input in variable at global


scope)
MUTABILITY/IMMUTABILITY OF
ARGUMENTS/PARAMETERS AND FUNCTION CALL

From the above example we can recall the concept learned in class XI
that Python variables are not storage containers, rather Python variables are
like memory references, they refer to memory address where the value is
stored,thus anychange in immutable type data will also change the
memory address. So any change to formal argument will not reflect
back to its corresponding actual argument and in case of mutable type,
any change in mutable type will notchangethe memoryaddressof
variable.
List is mutable i.e. data can be changed in the list
Example 1:
Because List is Mutable type, hence any change in formal
argument lst will not change the memory address, So changes
doneto lst will be reflected back to LIST1.
However if we formal ar GUMENT is assigned to some other variable or data
type then link will break and changes will not reflect back to ACTUAL ar GUMENT
Forexample(if insidefunctionupdateData()weassignmyListas:
myList = 20 OR myList = temp

Passing string to function


➢ Function can accept string as a parameter.
➢ As per Python, string is immutable type, so function canaccessthevalue
ofstringbutcannotalterthe string.
➢ To modify string, the trick is to take another string and concatenate the
modified value of parameter string in the newly created string.

Example 1:- Count the number of vowels in the string.


Example 2:- Count how many times the given character
is present in the string.
Example 3:- Convert the given string into different string.
Passing List to a Function
We can also pass List to any function as parameter.
Due to the mutable nature of List,functioncan alter the list of values in
place.
Itismostlyusedindatastructurelikesorting,stack, queue etc.

Example 1:- Program to double each value of the list.

Example 2:- Program to double the odd values and


half the Even values of a list.
Example 3:- Program to pass nested list as a matrix
and display all diagonal elements in the form of
matrix.

Example 4:- Print Sum and Average of all numbers and


return it in the form of tuple.
Passing tuples to function
➢ We can also pass tuples to function as parameter.
➢ Due to its immutability nature, function can only
access the values of tuples but cannot modify it.

Example 1:- Count how many Even and Odd numbers has entered.

Example 2:- A login program with the help of passing Tuple to a


function.
Passing Dictionary to Function
➢ Python also allows us to pass dictionaries to function.
➢ Due to its mutability nature,function can alter the keys or values of
dictionary in place.

Example 1:- Passing Dictionary with List and stores the no. of list
as key and frequency of no. as value.
Example 2:- Passing dictionary to function with key and value
and update value at that key.

Understanding of main( ) function


➢ By default every program starts their execution from main()
function. In Python including a main() function is not mandatory. It can
structure our Python programs in a logical way that puts the most
important components of the program in one function.
➢ We can get the name of current module executing by using built-in
variable name (2 underscore before and after of name).

By default the name of module will be _ _main( ) _ _

Recursion
➢ It is one of the most powerful tool in programming language. It
is a process where function calls itself again and again.
➢ Recursion basically divides the big problem in to small problems up
to the point where it can be solved easily, for example if we have to
calculate factorial of a 5, we will divide factorial of 5 as
5*factorial(4), then 4*factorial(3), then 3*factorial(2), then
2*factorial(1) and now factorial of 1 can be easily solved
without any calculation,now each pending function will be
executed in reverse order.
Condition for implementing Recursion:-
➢ It must contain BASE CONDITION i.e. at which point recursion
will end otherwise it will become infinite.
➢ BASE CONDITION is specified using “if” to
specify the termination condition.
➢ Execution in Recursion is in reverse order using STACK. It first divide
the large problem into smaller units and then starts solving from
bottom to top.
➢ It takes more memory as compare to LOOP statement because
with every recursion call memory space is allocated for local
variables.
➢ The computer may run out of memory if recursion becomes infinite
or termination condition not specified.
➢ It is less efficient in terms of speed and execution time.
➢ Suitable for complex data structure problems like TREE,
GRAPH etc.

Example 1: Calculate the factorial of the given number.

Example 2:- Print Fibonacci Series.

You might also like