Python Unit III
Python Unit III
UNIT-III
INTRODUCTION: 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.
Functions is a block of statements that return the specific task
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs
The function calls to reuse code contained in it over and over again.
PROGRAM ROUTINE:
The smaller code module is called as Routine
Routine is smaller block of well-organized and reusable code to perform a specified task
The routine is referred as function is used in all the places
Built-in- function in list such as len() sum() and stand function is print()
DEFINE FUNCTION:
Define a function with the def keyword, then write the function identifier (name) followed by
parentheses and a colon.
Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
FUNCTION DECLARATION:
def function_name(parameters):
#statement
Return(expression)
The def keyword used to define the function
The function_name is an identifier used to specify the name of the function. The function name is
used to call the function from some other part of the program
The arguments may contains zero or more number of arguments and are used to receive the value
from the calling place when its required for the calculation
Colon is used to terminate the function header and indicates that following indented statement are
part of the function
Types of Functions in Python
There are mainly two types of functions in Python.
Built-in library function: These are Standard functions in Python that are available to use.
User-defined function: We can create our own functions based on our requirements.
CALLING A FUNCTION:
By defining a function a name to function and defining its business logic. Function is called just by specifying
its name and passing argument if required
1
EXAMPLE:
def myFun(): # define function name
print(" Welcome to JavaTpoint")
myFun() # call to print the statement
CALLING VALUE –RETURNING FUNCTION:
A return statement is used to end the execution of the function call and “returns” the result (value of
the expression following the return keyword) to the caller.
The statements after the return statements are not executed.
A return statement is overall used to invoke a function so that the passed statements can be executed.
SYNTAX:
def fun():
statements
.
.
return [expression]
EXAMPLE:
def cube(x):
r=x**3
return r
A function may contain zero or more return statement. The return can be used only when required to
pass value back to the caller and use to return statement is not a mandatory.
The return statement can be situated anywhere in the function body after the function header
A return statement ends the execution of the function call and “return “
The return () takes zero or more values. any statement after return statement is not executed by the
compiler
If the return statement is without a value, the special value none is returned
Function with multiple return values:
The function with return exactly one value
The value may be any data type like an integer, a float, a list or a dictionary if want to return value like two
integer or float values it can be send using the return () statement by separating the value with commas.
The return values are received as single object as tuple in the calling place
SAMPLE PROGRAM:
2
def funcl(fname):
print(“hi”,fname,”welcome to python .world!”)
aname=input(“enter yourname:”)
func1(aname)
PARAMETER(ARGUMENT)PASSING:
Information can be passed into function from caller as argument, the argument are specified after the
function name, inside the parentheses
The argument are classified into two categories depends on the location of the arguments
Actual
Formal
Actual and formal arguments:
The argument which are used in function call is referred as actual arguments and the argument which are
used in the function definition is referred as formal arguments
The formal arguments are always identifiers, but the actual arguments may be either values, expression or
identifiers
def func1(a,b,c): //formal arguments
----------------------
----------------------
-----------------------
func1(x,y,z) //Actual arguments
REQURIED POSITIONAL ARGUMENT:
The required positional argument are simple type of arguments passing. These argument are passed to a
function in correct positional order not by names and types.
The number of arguments in function call should match exactly with the function definition
SAMPLE PROGRAM:
def funcl(strl,a,b,li):
print(“Argument value inside the function:”,strl,a,b,li)
myStr=”Department of Computer Science”
x=67
y=6.8
myList=[12,34,56,76,’hi’]
funcl(myStr,x,y,myList)
the programmer must take more care on including the arguments at the both the function call and definition.
There are two kind of problem exits
(i) Mismatch of number of arguments
3
(ii) Change of positional order of arguments leads to wrong calculation
To overcome the first problem python provides the facility with argument passing with default and variable
length arguments
The second problem will be override by using keywords arguments
PASS BY VALUE AND PASS BY REFERENCE:
Python supports pass by value and pass by reference
pass function arguments by reference, those arguments are only references to existing values. In contrast,
when you pass arguments by value, those arguments become independent copies of the original values.
The difference between pass-by-reference and pass-by-value is that modifications made to arguments
passed in by reference in the called function have effect in the calling function, whereas modifications made
to arguments passed in by value in the called function cannot affect the calling function.
call a function with a set of arguments, the data is copied into the function. This means that you can modify the
arguments however you please and that you won't be able to alter the state of the program outside the function
To pass the function(reference) to a variable which refers that the variable already exists in memory. Here, the
variable (the bucket) is passed into the function directly.
The default argument pass is pass by reference .passing the immutable identifier or value such as integer, float,
Boolean ,string ,tuple are passed as pass by value
The mutable identifier or value such as list ,dictionary ,set and user defined classes are passed as pass by
reference
Pass by reference -Pass by reference means that you have to pass the function(reference) to a variable which
refers that the variable already exists in memory.
Pass by value-pass a copy of actual variables in function as a parameter. Hence any modification on parameters
inside the function will not reflect in the actual variable.
SAMPLE PROGRAM:
def set_list(list):
4
list = ["A", "B", "C"]
return list
def add(list):
list.append("D")
return list
my_list = ["E"]
print(set_list(my_list))
print(add(my_list))
KEYWORD ARGUMENTS:
Keyword arguments are values that, when passed into a function, are identifiable by specific parameter
names.
A keyword argument is preceded by a parameter and the assignment operator, = .
Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
The keyword arguments are used to overcome the problem exists in the positional arguments
Keyword-only arguments mean whenever we pass the arguments(or value) by their parameter names at
the time of calling the function in Python in which if you change the position of arguments then there
will be no change in the output.
SAMPLE PROGRAM:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge(name="Prince", age=20)
nameAge(age=20, name="Prince")
On using keyword arguments, you will get the correct output because the order of argument doesn’t matter
provided the logic of your code is correct. But in the case of positional arguments, you will get more than one
output on changing the order of the arguments.
DEFAULT ARGUMENTS:
Python represent the function arguments that will be used if no arguments are passed to the function
call.
The default arguments are represented as argument_name = value in the function definition.
Default arguments in Python can be used with keyword and positional arguments.
Python has a different way of representing syntax and default values for function arguments.
Default values indicate that the function argument will take that value if no argument value is passed
during the function call.
The default value is assigned by using the assignment(=) operator of the form keywordname=value.
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
5
In the case of passing the keyword arguments, the order of arguments is important.
There should be only one value for one parameter.
The passed keyword name should match with the actual keyword name.
In the case of calling a function containing non-keyword arguments, the order is important.
SAMPLE PROGRAM:
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
student('John')
student('John', 'Gates', 'Seventh')
student('John', 'Gates')
student('John', 'Seventh')
The reason is the default values of the arguments are evaluated only once when the control reaches the function
Definition for the first time. After that, the same values(or mutable objects) are referenced in the subsequent
function calls.
VARIABLE LENGTH ARGUMENTS:
The number of arguments that will be passed into a function in advanced
Python allows us to handle this kind of situation through function call with variable length argument
VARIABLE SCOPE:
A variable scope specifies the region where we can access a variable.
the sum variable is created inside the function, so it can only be accessed within it
Python is not statically typed to declare variables before using them or declare their type. A variable is
created the moment first assign a value to it.
The location find a variable and also access it if required is called the scope of a variable.
Local variables are those that are initialized within a function and are unique to that function. It cannot
be accessed outside of the function.
Global variables are the ones that are defined and declared outside any function and are not specified to
any function. They can be used by any part of the program.
SAMPLE PROGRAM:
def f():
print(s)
s = "I love Geeksforgeeks"
f()
LOCAL SCOPE:
A variable defined inside a function belongs to the local scope of the function and can only scope of the
function and only be used inside that function
6
GLOBAL SCOPE:
A variable defined or created in main body of python program is called global scope variable. The
global scope are available to entire program
Global keyword
The python allows the modification of global variable in a function by using the global keyword, it
informs to the interpreter that the variable referred in the global keyword is defined as global variable in the
main body of the program and the modified variable in the function is not local variable
BUILT IN SCOPE:
The built in scope is the widest scope in python .All the reversed names defined in python built in
modules have a built in scope when the python doesn’t identifier in its local enclosing or global scope
RECURSION:
Python also accepts function recursion, which means a defined function can call itself. Recursion
is a common mathematical and programming concept.
It means that a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
It is a process in which a function calls itself directly or indirectly .
Using a recursive algorithm, certain problems can be solved quite easily.
The recursive function have to be designed in such a way to handle the infinite recursive
One prompt solution is making the recursive call conditionally
Advantages of using recursion
A complicated function can be split down into smaller sub-problems utilizing recursion.
Sequence creation is simpler through recursion than utilizing any nested iteration.
Recursive functions render the code look simple and effective.
Disadvantages of using recursion
A lot of memory and time is taken through recursive calls which makes it expensive for use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
SAMPLE PROGRAM:
def Recur_facto(n):
if (n == 0):
7
return 1
return n * Recur_facto(n-1)
print(Recur_facto(6))