6 FunctionsPDF
6 FunctionsPDF
You’re already familiar with the print(), input(), and len() functions. Python provides several
builtin functions like these, but you can also write your own functions. A function is like a
miniprogram within a program that performs a specific task.
Why functions?
● Creating a new function gives you an opportunity to name a group of statements, which
makes your program easier to read, understand, and debug.
● Functions can make a program smaller by eliminating repetitive code. Later, if you make
a change, you only have to make it in one place.
● Dividing a long program into functions allows you to debug the parts one at a time and
then assemble them into a working whole.
● Welldesigned functions are often useful for many programs. Once you write and debug
one, you can reuse it.
● A major purpose of functions is to group code that gets executed multiple times.
Without a function defined, you would have to copy and paste this code each time.
When you call the print() or len() function, you pass in values, called arguments in this context,
by typing them between the parentheses.
Userdefined functions
Definition of a function
Syntax
def functionName(parameters) :
statement(s)
● The keyword def introduces a function definition.
● It must be followed by the function name and the parenthesized list of formal
parameters.
● There can be number of arguments in a function.
● The statements that form the body of the function start at the next line, and must be
indented.
● Functions are used to perform a specific task multiple types.
● This code is executed when the function is called, not when the function is first defined.
● In code, a function call is just the function’s name followed by parentheses, possibly with
some number of arguments in between the parentheses.
● When the program execution reaches these calls, it will jump to the top line in the
function and begin executing the code there.
● When it reaches the end of the function, the execution returns to the line that called the
function and continues moving through the code as before.
Example
def coding(x):
print(x, "studies at coding blocks")
>>> coding("arushi")
arushi studies at coding blocks
>>> coding("jatin")
jatin studies at coding blocks
def multiply(x,y):
print(x*y)
>>> multiply(5,6)
30
>>> multiply(200,500)
100000
>>> multiply(398,890)
354220
Basically, in python it is not required to give each argument a datatype like other languages.
def student(name,rollno):
print("name",name,"rollno",rollno)
>>> student("AA",71)
name AA rollno 71
>>> student("BB",72)
name BB rollno 72
>>> student("CC",73)
name CC rollno 73
#Default parameters
def student(name="arushi",rollno=7): #default
print("name",name,"rollno",rollno)
Keyword Arguments
Functions can also be called using keyword arguments of the form kwarg=value.
All the keyword arguments passed must match one of the arguments accepted by the function
and their order is not important.
def names(a,b,c):
print(a)
print(b)
print(c)
def add(a,b):
print(a+b)
>>> a= add(6,7)
13
>>> print(a)
None
None here shows that there is no value that as been assigned to the function.
But if we use the return statement, the function will evaluate and return a value to the function.
def add(a,b):
return(a+b)
>>> a=add(7,8)
>>> print(a)
15
The global statement is a declaration which holds for the entire current code block.
>>> food()
i like pizza
To do alteration of a global variable within a function we declared the global variable in the
function using the keyword global.
Example
x="pizza"
def food():
global x #declaration of the global variable in the function
x="burgers" #alter
print("i like",x)
>>> food()
i like burgers
Local variable
The variables which are defined inside a function are treated as local variables.
All the alterations which are done to these variables, has no effect on the variables which are
defined outside the function. (even if they have the same names)
def places():
print("london") #local variable within a function
p="love for paris"
>>> print(p)
love for paris
>>> places()
london
Example:
def CB():
global f
print(f)
f = "Code in Python"
print(f)
>>> CB()
I am looking for a course in coding blocks!
Code in Python # variable f got updated
>>> print(f)
Code in Python
A Closure is a function object that remembers values in enclosing scopes even if they are not
present in memory.
A Nested Function is a function defined inside another function. It's very important to note
that the nested functions can access the variables of the enclosing scope.
def outer():
x="local"
def inner():
print(x)
inner()
print(x)
>>> outer()
local
local
NonLocal
The nonlocal statement causes the listed identifiers to refer to previously bound variables in
the nearest enclosing scope excluding globals.
This is important because the default behavior for binding is to search the local namespace
first.
The statement allows encapsulated code to rebind variables outside of the local scope
besides the global (module) scope.
def outer():
x=10
def inner():
nonlocal x
x+=5
print(x)
inner()
print(x)
>>> outer()
15
15
Keyword Arguments
All the keyword arguments passed must match one of the arguments accepted by the function
and their order is not important.
def names(a,b,c):
print(a)
print(b)
print(c)
We use ‘ * ’ to unpack the list so that all elements of it can be passed as different
parameters.
def netflix(*myFav):
print(myFav)
wake up
breakfast
TV
('Sherlock', 'The Big Bang Theory', 'How I met your Mother')
reading
coding
Default arguments has to specified because if they will not then they will considered
as the part of the tuple.
wake up
breakfast
TV
('Sherlock', 'The Big Bang Theory', 'How I met your Mother',
'reading', 'coding')
coding
reading
We use ‘ ** ‘ to pack.
wakeup
breakfast
TV
('Sherlock', 'flash') #tuple
{'work': 'coding'} #dictionary
Lambda Function ; Syntactic Sugars
They are small anonymous functions created with the lambda keyword consisting of a
single expression which is evaluated when the function is called.
They are syntactically restricted to a single expression which will be evaluated and
returned.
Like nested function definitions, lambda functions can reference variables from the
containing scope.
Syntex
Example