Understanding User Defined Functions
Understanding User Defined Functions
Chapter 7
Functions
FUNCTIONS
Function can be defined as a named group of
instructions that accomplish a specific task when it is
invoked.
Once defined, a function can be called repeatedly from
different places of the program without writing all the
codes of that function everytime.
.
The Advantages of Function
• Increases readability..
• Reduces code length as same code is not required
to be written at multiple places in a program.
• makes debugging easier.
• Work can be easily divided among team members
and completed in parallel.
• Time reduced
addnum()
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11
def incrValue(num):
print("Parameter num has value:",num,"\nid =",id(num))
num = num + 5
print("num incremented by 5 is",num,"\nNow id is ",id(num))
number = int(input("Enter a number: "))
print("id of argument number is:",id(number))
incrValue(number)
Output:
Enter a number: 8
id of argument number is: 1712903328
number and num
Parameter num has value: 8 have the same id
id = 1712903328
num incremented by 5 is 13 The id of Num has changed.
Now id is 1712903408
Let us understand the above output through illustration
(see Figure 7.4):
2021-22
id
Number 1712903328
Before 8
Num
increment
id
1712903328
id
Number 1712903328
8
Num id
After 1712903408 5 added
increment to 8
13
Output:
The calculated mean is: 3.5250000000000004
Output:
Enter the number: 5
Factorial of 5 is 120
Note: Since multiplication is commutative 5! = 5*4*3*2*1 =
1*2*3*4*5
def fullname(first,last):
Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan
def sum(a=2,b=3,c=4):
return (a+b+c)
print(sum(10,4))
print(sum(10))
print(sum(10,4,1))
print(sum())
x,y,z=1,2,3
print(sum(x,z))
def calcpow(number,power):
result = 1
for i in range(1,power+1):
result = result * number
return result
Output:
Enter the value for the Base: 5
Enter the value for the Exponent: 4
5 raised to the power 4 is 625
Flow of Execution
Flow of execution can be defined as the order in which
the statements in a program are executed.
The Python interpreter starts executing the
instructions in a program from the first statement.
The statements are executed one by one, in the order
of appearance from top to bottom.
def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
return (area,perimeter)
Output:
Enter Length of the rectangle: 45
Enter Breadth of the rectangle: 66 Multiple values in Python are returned throu
Area is: 2970.0
Perimeter is: 222.0
Program 7-13 Write a program that simulates a traffic light . The program
should consist of the following:
1. A user defined function trafficLight( ) that accepts input from the user,
displays an error message if the user enters anything other than RED,
YELLOW, and GREEN.
2. Function light() is called and following is displayed depending upon
return value from light().
a) “STOP, your life is precious” if the value
returned by light() is 0.
b) “Please WAIT, till the light is Green “ if the value returned by
light() is 1
c) “GO! Thank you for being patient” if the value returned by light()
is 2.
3. A user defined function light() that accepts a string as input and
returns 0 when the input is RED, 1 when the input is YELLOW and 2
when the input is GREEN. The input should be passed as an argument.
4. Display “ SPEED THRILLS BUT KILLS” after the function trafficLight( )
is executed.
def trafficLight():
signal = input("Enter the colour of the traffic light:
") if (signal not in ("RED","YELLOW","GREEN")):
FUNCTIONS 159
print("Please enter a valid Traffic Light colour in CAPITALS")
else:
value = light(signal) #function call to light()
if (value == 0):
print("STOP, Your Life is Precious.")
elif (value == 1):
print ("PLEASE GO SLOW.")
else:
print("GO!,Thank you for being patient.")
def light(colour):
if (colour == "RED"):
return(0);
elif (colour == "YELLOW"):
return (1)
else:
return(2)
trafficLight()
print("SPEED THRILLS BUT KILLS")
Output:
Enter the colour of the traffic light: YELLOW
PLEASE GO SLOW.
SPEED THRILLS BUT KILLS
SCOPE OF a VaRIaBLE
Every variable has a well-defined accessibility.
myFunc1()
print(" num outside ",num)
print(" y outside ",y)
Output:
num value = 5
y value = 10
num outside 5 Traceback (most recent
call last):
File "C:\NCERT\Prog [Link]", line 9, in <module>
print("Accessing y outside myFunc1 ",y)
NameError: name ‘y’ is not defined
2021-22
>>> Max((23,4,56))
56
min(sequence) >>> min([1,2,3,4])
or 1
min(x,y,z,...) >>> min("Sincerity")
'S'
>>> min(23,4,56)
4
pow(x,y[,z]) >>> pow(5,2)
25.0
>>> pow(5,2,4)
1
sum(x[,num]) >>> sum([2,4,7,3])
16
>>> sum([2,4,7,3],3)
19
>>> sum((52,8,4,2))
66
len(x) >>> len(“Patience”)
8
>>> len([12,34,98])
3
>>> len((9,45))
2 >>>len({1:”Anuj”,2:”Razia”,
3:”Gurpreet”,4:”Sandra”})
4
Module
a module is a grouping of functions.
The program is divided into different parts under
different levels, called modules.
To use a module, we need to import the module.
import modulename1 [,modulename2, …]
[Link]()
(A) Built-in Modules
commonly used modules and the frequently used
functions that are found in those modules:
• math
• random
• statistics Remember, Python is case sensitive. All the mo
•
Function Example
Syntax Output
[Link](x) >>> [Link](-9.7)
-9
>>> [Link] (9.7)
10
>>> [Link](9)
9
[Link](x) >>> [Link](-4.5)
-5
>>> [Link](4.5)
4
>>> [Link](4)
4
[Link](x) >>> [Link](6.7)
6.7
>>> [Link](-6.7)
6.7
>>> [Link](-4)
4.0
[Link](x) >>> [Link](5)
120
[Link](x,y) >>> [Link](4,4.9)
4.0
>>> [Link](4.9,4.9)
0.0
>>> [Link](-4.9,2.5)
-2.4
>>> [Link](4.9,-4.9)
0.0
Note:
2021-22
FUNCTIONS 167
Example 7.5
>>> from random import random
>>> random()
#Function called without the module
name
Good Programming Practice: Only using the required function(s) rather than importing a module saves memory.
Output:
0.9796352504608387
Example 7.6
>>> from math import ceil,sqrt
>>> value = ceil(624.7)
>>> sqrt(value)
Output:
25.0
FUNCTIONS 167
>>> from math import trunc
>>> sqrt(trunc(625.7))
Output:
25.0
Program 7-16 Create a user defined module basic_
math that contains the following
user defined functions:
1. To add two numbers and return their sum.
2. To subtract two numbers and return their difference. """Docstrings""" is also called Python
documentation strings. It is a multiline comme
3. To multiply two numbers and return their product.
4. To divide two numbers and return their quotient
and print “Division by Zero” error if the
denominator is zero.
5. Also add a docstring to describe the module. After
creating module, import and execute functions.
#Beginning of module
def addnum(x,y):
return(x + y)
def subnum(x,y):
return(x - y)
def multnum(x,y):
return(x * y)
def divnum(x,y):
if y == 0:
print ("Division by Zero Error")
else:
return (x/y) #End of module
Output:
#Statements for using module basic_math
>>> import basic_math
#Display descriptions of the said module
>>> print(basic_math. doc )
SUMMaRY
NOTES
• In programming, functions are used to achieve
modularity and reusability.
• Function can be defined as a named group of
instructions that are executed when the function
is invoked or called by its name. Programmers
can write their own functions known as user
defined functions.
• The Python interpreter has a number of functions
built into it. These are the functions that are
frequently used in a Python program. Such functions
are known as built-in functions.
• An argument is a value passed to the function
during function call which is received in a parameter
defined in function header.
• Python allows assigning a default value to
the parameter.
• A function returns value(s) to the calling function
using return statement.
• Multiple values in Python are returned through
a Tuple.
• Flow of execution can be defined as the order in
which the statements in a program are executed.
• The part of the program where a variable is
accessible is defined as the scope of the variable.
• A variable that is defined outside any particular
function or block is known as a global variable. It
can be accessed anywhere in the program.
• A variable that is defined inside any function or block
is known as a local variable. It can be accessed only
in the function or block where it is defined. It exists
only till the function executes or remains active.
• The Python standard library is an extensive
collection of functions and modules that help the
programmer in the faster development of programs.
• A module is a Python file that contains definitions of
multiple functions.
• A module can be imported in a program using
import statement.
• Irrespective of the number of times a module is
imported, it is loaded only once.
• To import specific functions in a program from a
module, from statement can be used.
2021-22
170 COMPUTER SCIENCE – CLASS XI
NOTES
EXERCISE
1. Observe the following programs carefully, and
identify the error:
a) def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call
b) from math import sqrt,ceil
def calc():
print cos(0)
calc() #function call
c) mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function call
d) def findValue( vall = 1.1, val2,
val3): final = (val2 + val3)/
vall print(final)
findvalue() #function call
e) def greet():
return("Good morning")
greet() = message #function call
aCTIVITY-BaSED QUESTIONS
NOTES
Note: Writing a program implies:
• Adding comments as part of documentation
• Writing function definition
• Executing the function through a function call
1. To secure your account, whether it be an email,
online bank account or any other account, it is
important that we use authentication. Use your
programming expertise to create a program using
user defined function named login that accepts
userid and password as parameters (login(uid,pwd))
that displays a message “account blocked” in case
of three wrong attempts. The login is successful if
the user enters user ID as "ADMIN" and password
as "St0rE@1". On successful login, display a
message “login successful”.
2. XYZ store plans to give festival discount to its
customers. The store management has decided to
give discount on the following criteria:
>=2000 10%
2021-
22
174 COMPUTER SCIENCE – CLASS XI