0% found this document useful (0 votes)
9 views34 pages

UNIT III Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views34 pages

UNIT III Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

ADITYA ENGINEERING COLLEGE (A)

PYTHON PROGRAMMING
(191ES3T11)
By

Mr. B. Vinay Kumar


Dept. of Information Technology
Aditya Engineering College(A)
Surampalem.
Aditya Engineering College (A)

UNIT III

Functions Modules

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

Contents:

• Functions: Function Parameters, Local variables, the global statement,


Default Argument values, Keyword Arguments, VarArgs parameters, the
return statement. Anonymous Functions (lambda), Doc strings.

• Modules: The from import statement, A module’s name, Making your


own modules, the dir function, packages.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Syntax of Function Aditya Engineering College (A)

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__)

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

How to call a function in python?


• Once we have defined a function, we can call it from another function,
program or even the Python prompt.
• To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
Hello, Paul. Good morning!

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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)

Types Of Python Function Arguments


• There are four types of Python Functions.

• Required arguments (Positional Arguments)


• Keyword arguments
• Default arguments
• Variable-length Arguments (varArgs).

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.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

function_keyword.py

def func(a, b=5, c=10):


print ('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

Default Argument Values


• For some functions, you may want to make some parameters optional and use
default values in case the user does not want to provide values for them.
• Note that the default argument value should be a constant. More precisely, the
default argument value should be immutable.

def say(message, times=1):


print (message * times)
say('Hello')
say('World', 5)

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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.

• We can have both normal and keyword variable number of arguments

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

function_varargs.py
# Python program to illustrate
# *argv for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)

myFun('Hello', 'Welcome', 'to', 'Aditya')

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

# Python program to illustrate


# **args for variable number of keyword arguments
def myFun(**args):
for key, value in args.items():
print ("%s = %s" %(key, value))

# Driver code
myFun(first ='Aditya', mid ='Engg.', last='College')

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

• When we declare a starred parameter such as *param , then all the


positional arguments from that point till the end are collected as a
tuple called 'param'.
• Similarly, when we declare a double-starred parameter such as
**param , then all the keyword arguments from that point till the end
are collected as a dictionary called 'param'.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

• 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)

• Furthermore, a function can return another function.


def is_called():
def is_returned():
print("Hello")
return is_returned
>>> new = is_called() # Outputs "Hello"
>>> new()
Here, is_returned() is a nested function which is defined and returned
each time we call is_called().
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()

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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)

• In fact, any object which implements the special __call__() method is


termed callable. So, in the most basic sense, a decorator is a callable
that returns a callable.
• Basically, a decorator takes in a function, adds some functionality and
returns it.
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)

When you run the following codes in shell,


>>> ordinary()
I am ordinary
>>> # let's decorate this ordinary function
>>> pretty = make_pretty(ordinary)
>>> pretty()
I got decorated
I am ordinary

Python 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.

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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)

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

The global statement


• It is used to create global variables from a non-global scope i.e., inside a
function.
• You can specify more than one global variable using the same global
statement e.g. global x, y, z.
• Rules of global keyword:
• When we create a variable inside a function, it is local by default.
• When we define a variable outside of a function, it is global by default. You
don't have to use global keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect.
Python Programming B. Vinay Kumar Sunday, November 24, 2024
Aditya Engineering College (A)

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)

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

def Append(list):
list.append(1)
print (list)

list = [0]
Append(list)
print (list)
Output:
[0, 1]
[0, 1]

Python Programming B. Vinay Kumar Sunday, November 24, 2024


Aditya Engineering College (A)

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)

• Note that a return statement without a value is equivalent to return None.


• None is a special type in Python that represents nothingness. For example,
it is used to indicate that a variable has no value if it has a value of None.
• Every function implicitly contains a return None statement at the end unless
you have written your own return statement.
• You can see this by running print some_function() where the function
some_function does not use the return statement such as:
def some_function():
pass
• The pass statement is used in Python to indicate an empty block of
statements

Python Programming B. Vinay Kumar Sunday, November 24, 2024

You might also like