Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Functions in Python ST

The document discusses functions in Python. It defines functions as reusable blocks of code that perform specific tasks. There are two types of functions: built-in functions that are included in Python and user-defined functions that are defined by users. Functions are defined using the def keyword and syntax. Functions can take parameters and arguments, and can return values using the return statement. The document also covers variable scope, and different ways functions can be called, including required arguments, keyword arguments, default arguments, and variable length arguments.

Uploaded by

sanjoni.jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Functions in Python ST

The document discusses functions in Python. It defines functions as reusable blocks of code that perform specific tasks. There are two types of functions: built-in functions that are included in Python and user-defined functions that are defined by users. Functions are defined using the def keyword and syntax. Functions can take parameters and arguments, and can return values using the return statement. The document also covers variable scope, and different ways functions can be called, including required arguments, keyword arguments, default arguments, and variable length arguments.

Uploaded by

sanjoni.jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

2/17/2023

Functions in
Python

Need of Function
1. Dividing the program into separate well defined modules .
2. Code reuse is one of the most prominent reason to use functions.
3. Large program follows the DRY principle, that is “Don’t Repeat Yourself “.
4. Onces a function is written , it can be called multiple times within the same
or by a different program.
5. Correspondingly , a bad repetitive code abides by WET principle that is
“Write Everything Twice “ or “We Enjoy Typing”.
6. Function provide better modularity for your application and a high degree
of code reuse .

Function Introduction
Function is a block of organized and reusable program code
that performs a single , specific and well- defined task .

Two basic types of function in Python :

1. Built-in Function
2. User defined function

1
2/17/2023

Built-in functions - Functions that are built into

Python.

Ex: abs(), ascii(), bool()………so on….


integer = -20
print('Absolute value of -20 is:', abs(integer))

Output:
Absolute value of -20 is: 20

User-defined functions - Functions defined by the

users themselves.

def add_numbers(x,y):
sum = x + y
return sum

print("The sum is", add_numbers(5, 20))


Output:
The sum is 25

Function Definition: Syntax

def function_name():

Statement block

return [expression ]

Note: Before calling a function you must define it .

2
2/17/2023

Function Definition: Example


Execute xyz function
def xyz(): Output:
Before calling
for i in range(4): Hello all
Hello all
Return from function Hello all
print("Hello all") Hello all
After calling
This line
Start
print('Before calling')
Calling to xyz function
xyz()

print('After calling')

Parameters and arguments:


Parameters are specified during the definition of function
while Arguments are passed during the function call.

Example:
def add(a,b): #function definition
#here a and b are parameters
return a+b
result=add(12,13) #12 and 13 are
arguments

print(result)
Output:25

def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
● The return statement is used to exit a function and go back to the place from
where it was called. This statement can contain expression which gets
evaluated and the value is returned.
● If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.

3
2/17/2023

The Return Statement

● The return statement is used for two


things .
● Return a value to the caller
● To end and exit a function and go back to its
caller .

Return Statement : Example


In x 10 comes
def cube(x): 10
10
y=x*x*x 10
y=1000
return(y)

num=10 start 1000

10
result=cube(num)
1000
print(“Cube of “, num , “=” , result)
result=1000

EXAMPLE
def calculete(a,b):
total=a+b

diff=a-b

prod=a*b

div=a/b

mod=a%b
return total,diff,prod,div,mod

4
2/17/2023

a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)
Output:
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5

Variable Scope and Lifetime


● In python you cannot just access any variable from any part
of your program.
● Some of the variable not even exist for the entire duration
of a program .
● So for this purpose we must understand the two things
regarding this ,
1. Scope of the variable : part of the program in which a
variable is accessible is called its scope
2. Lifetime of the variable : Duration for which the variable
exists is called its lifetime .

Variable Scope: Local and Global Variable


Global Variable:

● are those variables which are defined in the main body of the program .
● They are visible throughout the program file.

Local Variable:

● A variable which is defined within a function is called as local to that


function only .
● A local variable can be accessed from the point of its definition until the
end of the function in which it is defined

5
2/17/2023

Local and Global Variable Example


num1=10 # global variable
print(“Global Variable is “, num1)
def func(num2)
print(“In function Local Variable”, num2)
num3=30
print(“in Function Local Variable “, num3)
func(20)
print( “ Print Global Variable Again “ , num1)
print(“Local Variable Again “, num3 ) # error comes not run

Using the Global Statement


● To define a variable inside a function as global , you must use the global
statement .

Global Statement : Example


num1=10 # global variable
print(“Global Variable is “, num1)
def func(num2):
global num3
num3=30
print(“In function Local Variable”, num2)
print(“in Function Local Variable “, num3)
func(20)
print( “ Print Global Variable Again “ , num1)
print(“Local Variable Again “, num3 ) # Executes properly no error due to Global
Statement

6
2/17/2023

OUTPUT
Global Variable is 10
In function Local Variable 20
in Function Local Variable 30
Print Global Variable Again 10
Local Variable Again 30
>

Function Parameter or Arguments

1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable Length Arguments

Required Arguments
● The arguments are passed to a function in correct
position order .
● The number of arguments in the function call
should exactly match with the number of
arguments specified in the function definition .

7
2/17/2023

Required Arguments :Program


def display(name , roll_no, marks):

print(“The name is”, name)

pankaj
print(“The roll no is”, roll_no) 10

print(“Marks is”, marks)


68.90
name1=”pankaj”

rl=10

mymarks=68.90

display(name1, rl,mymarks)

#Keyword Arguments
● When we call a function with some values, these values get assigned to the
arguments according to their position.
● Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed.
(Or)
● 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.

There are two advantages -


● one, using the function is easier since we do not

need to worry about the order of the arguments.


● Two, we can give values to only those

parameters which we want, provided that the


other parameters have default argument values.

8
2/17/2023

Keyword Arguments : Program


def display(name , roll_no, marks):
print("The name is", name)
print(" roll no is", roll_no)
print("Marks is", marks)

display(marks=70.20, roll_no=10, name="Pankaj”)

EXAMPLE

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)

Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Default Arguments
● Python allows users to specify function arguments that can have default values.
● This means that a function can be called with fewer arguments that it is defined
to have.
● If the function accepts three parameters , but function call provide only two
arguments , then the third parameter will be assigned the default ( already
specified) Value
● The default value to an argument is provided by using the assignment
operator(=)
● User can specify default value for one or more argument

9
2/17/2023

Default Arguments: Program


def display(name , roll_no, marks=80):

print("The name is", name)

print(" roll no is", roll_no)

print("Marks is", marks)

display(roll_no=10,name="Pankaj”)

Variable-length arguments
● Sometimes you may need more arguments to process function than you mentioned in
the definition. If we don’t know in advance about the arguments needed in function, we
can use variable-length arguments also called arbitrary arguments.

● For this an asterisk (*) is placed before a parameter in function definition which can
hold non-keyworded variable-length arguments and a double asterisk (**) is placed
before a parameter in function which can hold keyworded variable-length arguments.

● If we use one asterisk (*) like *var, then all the positional arguments from that point till
the end are collected as a tuple called ‘var’ and

● if we use two asterisks (**) before a variable like **var, then all the positional
arguments from that point till the end are collected as a dictionary called ‘var’.

Variable-Length Arguments: Program


def func(name,*fav_subject):
print("\n",name, "likes to read")
for subject in fav_subject:
print(subject)
func("Ganesh", "Math","PPS", "Data Structure")
func("Ram", "Physics")
func("Maya")

10
2/17/2023

OUTPUT
Ganesh likes to read
Math
PPS
Data Structure

Ram likes to read


Physics

Maya likes to read


>

Example
def display(farg,**kwargs):
print('formal argument =',farg)
for x,y in kwargs.items(): #items will give key value pair
print('Key = ',x, ':', 'value = ', y)
display(5, rno = 10)
print()
display(5, rno =10,name = 'Prakash')

Output
formal argument = 5
Key = rno : value = 10

formal argument = 5
Key = rno : value = 10
Key = name : value = Prakash

11
2/17/2023

Example
def display(farg,**kwargs):
print('formal argument =',farg)
for x,y in kwargs.items(): #items will give key value pair
print('Key = ',x, ':', 'value = ', y)
sct = {'A':'hi', 'B':'Hello'}
display(5,**sct)

Output
formal argument = 5
Key = A : value = hi
Key = B : value = Hello

Lambda Function or Anonymous Function


● Function that is created using lambda keyword not using def
keyword.
● Lambda function are just needed where they have been created
and can be used anywhere a function required.
● Lambda function contains only a single line .
● Syntax: lambda arguments : Expression
● Example : sum=lambda x, y : x+y

print(“Sum=”, sum(3,5))

12
2/17/2023

Lambda Functions : Key points


● Lambda function have no name
● Lambda function can take any number of arguments
● Lambda function just return one value
● Lambda function definition does not have any explicit return statement
but it always contains an expression which is returned
● They are a one-line version of a function and hence cannot contain
multiple expression
● Lambda function can not access global variable
● You can use Lambda function in normal function

Write a Python function that takes two lists and returns True if they have at least
one common member.

def common_data(list1, list2):


for x in list1:
for y in list2:
if x == y:
result= True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))

output
True
True
None

13
2/17/2023

We can also pass functions as parameters to other functions

def display(fun):
return ‘Hi’ + fun
def message()
return ‘How are you?’
print(display(message()))
OUTPUT
Hi How are you?

Documentation String
● Docstring (Documentation String) serve the same purpose as that of comments,
as they are designed to explain code.
Output:
Hello world !!!
def func() The program just print a message.
It will dislay Hello world!!!
“””The program Just prints a message .

It will display Hello world !!!”””

print(“Hello world!!!”)

print(func.__doc__) # this one important

Documentation String : Key points


● Triple quotes are used to extend the docstring to multiple
lines.
● The docstring specified can be accessed through the __doc__
attribute of the function.
● As the first line , it should always be short and concise
highlighting the summary of the object purpose .

14
2/17/2023

IMPORTANT
● In Python integers, floats, strings and tupes are immutable i.e their data cannot
be modified
● when we try to change their values a new objec is created with the modified
value
● on the other hand lists and dictionaries are mutable
● when we change their data same object is modified and new object is not
created

print("Hello world") OUTPUT


def modify(lst): [2, 3, 4, 5, 9] 140553332113984
lst.append(9) [2, 3, 4, 5, 9] 140553332113984
print(lst,id(lst))
lst = [2,3,4,5]
modify(lst)
print(lst,id(lst))

def modify(x): OUTPUT


x = 15
print(x,id(x))
x = 10
15 10742984
modify(x) 10 10742824
print(x,id(x))

15
2/17/2023

RECURSIVE FUNCTIONS
#recusive function to calculate Factorial
def factorial(n):
if n == 0:
result = 1
else:
result = n * factorial(n-1)
return result

for i in range(1,11):
print(i, ' ', factorial(i))

OUTPUT
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800

GENERATORS
• Are Functions that return a sequence of values
• It is written like an ordinary function but it uses
‘yield’ statement

16
2/17/2023

Example
def gennum(x,y): def gennum(x,y):
while x<= y: while x<= y:
yield x yield x
x+=1
x+=1
g = gennum(10,20)
g = gennum(10,20)
lst = list(g)
for i in g: for i in lst:
print(i, end =' ') print(i, end =' ')

Introduction to Modules
● Modules allows you to reuse one or more function in your programs, even in the
program in which those functions have not defined .
● Function helps us to reuse a particular piece of code.
● Module is a file with .py extension that has definition of all functions and
variable that you would like to use even in other programs .
● The program in which you want to use functions and variables that defined in
the module will simply import that particular module( or .py file).
● The basic way to use module is to add import module_Name as the first
line of your program then adding module_name.var to access and values
with the name var in the module .

Using Standard library module


import sys # sys is standard library module

print(“ \n Python Path = \n” , sys.path )

● In above code , we import the sys module using the import statement to
use its functionality related to the python .

17
2/17/2023

The from……. import statement


● A module may contain definition for many variable and function. When
you import a module , you can use any variable or function defined in
that module, but if you want to use only selected variable or function ,
then you can use the from………….import statement.

from math import pi

print(“PI=”, +pi)

Making your own modules

● You can easily create as many modules as


you want .
● Every python program is a module

Making your own modules : Program


mymodule.py file Find.py file
def large (a,b):
if(a>b): Import mymodule
return a print(mymodule.large(50,1
else 00)
print(mymodule.large(100,
return b
200)

Output :
100
200

18
2/17/2023

Standard Library Modules


● Python supports three types of modules 1. Those written by the programmer 2.
Those that are installed from external sources 3. Those that pre installed with
python .
● Modules that are pre- installed in python are together know as the standard
library .
● Some useful modules in the standard library are string , re , datetime , math ,
random , os , multiprocessing , subprocess , socket , emails , json , and sys .
● You can use these modules for performing tasks like string parsing , data
serialization , testing , debugging etc.

Standard Library Modules: Example


import time

localtime = time.asctime(time.localtime(time.time()))

print(“Local current time :” , localtime)

Standard Library Modules: Example


import calendar

print(calendar.moth(2020,10)

19
2/17/2023

Packages in Python
● Package is a hierarchical file directory structure that has modules and other
packages within it .
● Like modules you can easily create packages in python .
● Every package in python is a directory which must have a special file called
_init_.py.
● This file may not have single line of code.
● It is simply added to indicate that this directory is not an ordinary directory and
contains a python package .
● In your programs you can import a package in the same way as you import any
module .

Program on Package
● To create a package called mypackage , create a directory called
mypackage having the module mymodule.py and the _init_.py file.
● Now to use mymodule in a program you must import it . This can
be two ways
● 1. import mypackage.mymodule
● 2. from mypackage import mymodule

20

You might also like