UNIT III Functions
UNIT III Functions
PYTHON PROGRAMMING
(191ES3T11)
By
UNIT III
Functions Modules
Contents:
Introduction
• 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.
• In Python, a function is a group of related statements that performs a specific
task.
• Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
• Furthermore, it avoids repetition and makes the code reusable.
def function_name(parameters):
"""docstring"""
statement(s)
• Above shown is a function definition that consists of the following components.
• Keyword def that marks the start of the function header.
• A function_name to uniquely identify the function. Function naming follows the same
rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body. Statements must have
the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)
Example of a function
def greet(name):
""" This function greets to the person
passed in as a parameter """
print("Hello, " + name + ". Good morning!")
>>> dir(__builtins__)
Function Parameters
• A function can take parameters, which are values you supply to the function
so that the function can do something utilizing those values.
• These parameters are just like variables except that the values of these
variables are defined when we call the function and are already assigned
values when the function runs.
• Parameters are specified within the pair of parentheses in the function
definition, separated by commas.
• When we call the function, we supply the values in the same way.
• Note the terminology used - the names given in the function definition are
called parameters whereas the values you supply in the function call are
called arguments.
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)
Required arguments
• Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
def printme( str ):
"This prints a passed string into this function"
print(str)
printme() # Now you can call printme function
• To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error.
Keyword arguments
• If you have some functions with many parameters and you want to specify
only some of them, then you can give values for such parameters by naming
them - this is called keyword arguments - we use the name (keyword)
instead of the position (which we have been using all along) to specify the
arguments to the function.
• The idea is to allow caller to specify argument name with values so that
caller does not need to remember order of parameters.
function_keyword.py
func(3, 7)
func(25, c=24)
func(c=50, a=100)
VarArgs parameters
• Sometimes you might want to define a function that can take any number of
parameters, i.e. variable number of arguments, this can be achieved by using
the stars.
function_varargs.py
# Python program to illustrate
# *argv for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)
# Driver code
myFun(first ='Aditya', mid ='Engg.', last='College')
Decorators in Python
• Python has an interesting feature called decorators to add functionality to
an existing code.
• This is also called metaprogramming because a part of the program tries
to modify another part of the program at compile time.
• Everything in Python (Yes! Even classes), are objects.
• Functions are no exceptions, they are objects too (with attributes).
• Various different names can be bound to the same function object.
• Here is an example.
def first(msg):
print(msg)
>>> first("Hello")
>>> second = first
>>> second("Hello")
Output
• Hello
• Hello
• When you run the code, both functions first and second give the same
output. Here, the names first and second refer to the same function
object.
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Higher order functions Aditya Engineering College (A)
• Functions that take other functions as arguments are also called higher order functions.
• Ex: map, filter and reduce
def inc(x):
return x + 1
def dec(x):
return x - 1
def operate(func, x):
result = func(x)
return result
• We invoke the function as follows.
>>> operate(inc,3)
4
>>> operate(dec,3)
2 Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)
Inner Functions
def parent():
print("Printing from the parent() function")
def first_child():
print("Printing from the first_child() function")
def second_child():
print("Printing from the second_child() function")
second_child()
first_child()
>>> parent()
First-Class Objects
• In Python, functions are first-class objects. This means that functions can be passed
around and used as arguments, just like any other object (string, int
, float, list, and so on). Consider the following three functions:
def say_hello(name):
return f"Hello {name}"
def be_awesome(name):
return f"Yo {name}, together we are the awesomest!"
def greet_bob(greeter_func):
return greeter_func("Bob")
>>> greet_bob(say_hello)
'Hello Bob'
>>> greet_bob(be_awesome)
'Yo Python
Bob,Programming
together we are the awesomest!'
B. Vinay Kumar Sunday, November 24, 2024
Returning Functions From Functions Aditya Engineering College (A)
def parent(num):
def first_child():
return "Hi, I am Emma"
def second_child():
return "Call me Liam"
if num == 1:
return first_child
else: return second_child
>>> first = parent(1)
>>> second = parent(2)
>>> first()
'Hi, I am Emma'
>>>
Python second()
Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)
Local Variables
• When you declare variables inside a function definition, they are not
related in any way to other variables with the same names used outside
the function - i.e. variable names are local to the function.
• This is called the scope of the variable.
• All variables have the scope of the block they are declared in starting
from the point of definition of the name.
Example: function_local.py
x = 50
def func(x):
print ('x is', x)
x=2
print ('Changed local x to', x)
func(x)
print ('x is still', x)
function_global.py
x = 50
def func():
global x
print ('x is', x)
x=2
print ('Changed global x to', x)
func()
print ('Value of x is', x)
Pass-by-object-reference
• Python is different.
• As we know, in Python, “Object references are passed by value”.
• A function receives a reference to (and will access) the same object in
memory as used by the caller.
• However, it does not receive the box that the caller is storing this object in;
as in pass-by-value, the function provides its own box and creates a new
variable for itself.
• Let’s try
def Append(list):
list.append(1)
print (list)
list = [0]
Append(list)
print (list)
Output:
[0, 1]
[0, 1]
def reassign(list):
list = [0, 1]
print (list)
list = [0]
reassign(list)
print (list)
Output:
[0, 1]
[0]
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)