0% found this document useful (0 votes)
7 views31 pages

Understanding User Defined Functions

Uploaded by

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

Understanding User Defined Functions

Uploaded by

pauldurai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FUNCTIONS 149

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

USER DEFINED FUNCTIONS


standard library function can directly call these functions in our
program without defining them.
We can define our own functions while writing the program.
Such functions are called user defined functions.
Creating User Defined Function
A function definition begins with def (short for define). The
syntax for creating a user defined function is as follows:

• The items enclosed in "[ ]" are called parameters and


they are optional. Hence, a function may or may not
have parameters. Also, a function may or may not
return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming
identifiers also applies for function naming.
• The statements outside the function indentation
are not considered as part of the function.
P1 : Write a user defined function to add 2 numbers and display their sum.
def addnum():
fnum = int(input("Enter first number: ")) snum =
int(input("Enter second number: ")) sum = fnum +
snum
print("The sum of ",fnum,"and ",snum,"is ",sum)

addnum()
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11

Arguments and Parameters


An argument is a value passed to the function during the
function call which is received in corresponding
parameter defined in function header.
P2: Write a program using a user defined function that displays sum of first n
natural numbers, where n is passed as an argument.

def sumSquares(n): #n is the parameter


sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)

num = int(input("Enter the value for n: "))


sumSquares(num) #function call
FUNCTIONS 151
P3: Write a program using user defined function that accepts an integer and
increments the value by 5.
Also display the id of argument (before function call), id of parameter before
increment and after increment.

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

P7 Write a program using a user defined function


myMean() to calculate the mean of
floating values stored in a list.

def myMean(myList): #function to compute means of values in list


total = 0
count = 0
for i in myList:
total = total + i #Adds each element i to total
count = count + 1 #Counts the number of elements
mean = total/count #mean is calculated
print("The calculated mean is:",mean)
myList = [1.3,2.4,3.5,6.9]
myMean(myList)

Output:
The calculated mean is: 3.5250000000000004

P7 Write a program using a user defined function


calcFact() to calculate and display the
factorial of a number num passed as an
argument.
FUNCTIONS 153
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)

num = int(input("Enter the number: "))


calcFact(num)

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

(A) String as Parameters


user may need to pass string values as an argument
P8 Write a program using a user defined
function that accepts the first name and
lastname as arguments concatenate
them to get full name and displays the
output as:
Hello full name
For example, if first name is Gyan and lastname is
Vardhan, the output should be:
Hello Gyan Vardhan

def fullname(first,last):

fullname = first + " " + last


print("Hello",fullname)
first = input("Enter first name:
") last = input("Enter last name:
") fullname(first,last)

Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan

(B) Default Parameter


Python allows assigning a default value to the parameter.
A default value is a value that is pre decided and
Assigned to the parameter when the function call does
not have its corresponding argument.

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

Let us consider few more function definition headers:

def calcInterest(principal = 1000, rate, time = 5):

def calcInterest(rate,principal = 1000,time = 5):

Functions Returning Value


A function may or may not return a value when called.
The return statement returns the values from the
function.

.They do not return any value. Such functions are called


void functions.
But a situation may arise, where in we need to send
value(s) from the function to its calling function. This is
done using return statement.

The return statement does the following:


• returns the control to the calling function.
• return value(s) or None.

Program 7-10 Write a program using user defined


function calcPow() that accepts base
and exponent as arguments and returns
the value Baseexponent where Base and
exponent are integers.
FUNCTIONS 155

def calcpow(number,power):
result = 1
for i in range(1,power+1):
result = result * number
return result

base = int(input("Enter the value for the Base: "))


expo = int(input("Enter the value for the Exponent: "))
answer = calcpow(base,expo)
print(base,"raised to the power",expo,"is",answer)

Output:
Enter the value for the Base: 5
Enter the value for the Exponent: 4
5 raised to the power 4 is 625

• Function with no argument and no return value


• Function with no argument and with return value(s)
• Function with argument(s) and no return value
• Function with argument(s) and return value(s)

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.

When the interpreter encounters a function definition,


the statements inside the function are not executed
until the function is called. Later, when the interpreter
encounters a function call, there is a little deviation
in the flow of execution. In that case, instead of going
to the next statement, the control jumps to the called
function and executes the statement of that function.
After that, the control comes back the point of function
call so that the remaining statements in the program
can be executed. Therefore, when we read a program,
we should not simply read from top to bottom. Instead,
we should follow the flow of control or execution. It is
also important to note that a function must be defined
before its call within a program.
Program 7-11 Program to understand the low of
execution using functions.
#Program 7-11
#print using functions
helloPython() #Function Call

def helloPython(): #Function definition


print("I love Programming")

On executing the above code the following error is


produced:
Traceback (most recent call last):
File "C:\NCERT\Prog [Link]", line 3, in <module>
helloPython() #Function Call
NameError: name 'helloPython' is not defined
The error ‘function not defined’ is produced even
though the function has been defined. When a function
call is encountered, the control has to jump to the
function definition and execute it. In the above program,
since the function call precedes the function definition,
the interpreter does not find the function definition
and hence an error is raised.
2021-22
FUNCTIONS 157

That is why, the function definition should be made


before the function call as shown below:
def helloPython(): #Function definition
print("I love Programming")

helloPython() #Function Call


[2] def Greetings(Name):#Function Header Figure 7.5 explains
[3] print("Hello "+Name) the flow of execution
for two programs.
The number in
[1] Greetings("John") #Function Call square brackets
[4] print("Thanks") shows the order of
execution of the
[4] def RectangleArea(l,b): #Function Header statements.
[5] return l*b Sometime, a
function needs to
return multiple
[1] l = input("Length: ") b = input("Breadth: ") values which may be
[2] Area = RectangleArea(l,b) returned using tuple.
[3][6] print(Area) print("thanks")
[7] #Function Call Program 7-12 shows
[8] a function which
returns two values
area and perimeter
of rectangle using
tuple.
Figure 7.5: Order of execution of statements
Program 7-12 Write a program using user defined function that accepts length and
breadth of a rectangle and returns the area and perimeter of the
rectangle.

def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
return (area,perimeter)

l = float(input("Enter length of the rectangle: "))


b = float(input("Enter breadth of the rectangle:
"))
area,perimeter = calcAreaPeri(l,b)
print("Area is:",area,"\nPerimeter is:",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.

Variable Scope The part of the program where a variable is


accessible can be defined as the scope
of that variable.
A variable can have one of the following two scopes:
Global Scope Local Scope
A variable that has global scope is known as a
global variable
A variable that has a local scope
Figure 7.6: Scope of a variable
is known as a local
variable.
(A) Global Variable
Variable that is defined outside any function or any
block is known as a global variable.
Any change made to the global variable will impact all
the functions in the program where that variable can
be accessed.

(B) Local Variable


A variable that is defined inside any function or a block
is known as a local variable.
It can be accessed only in the function or a block
where it is defined.
It exists only till the function executes.

Program 7-14 Program to access any variable outside the function


num = 5
def myFunc1( ):
y = num + 5
print(" num value = ",num)
print("y value=",y)

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

Global variable output, Local variable output


Note:
• Any modification to global variable is permanent and
affects all the functions where it is used.
• If a variable with the same name as the global variable
is defined inside a function, then it is considered local
to that function and hides the global variable.
• If the modified value of a global variable is to be used
outside the function, then the keyword global should
be prefixed to the variable name in the function.
FUNCTIONS 161

Program 7-15 Write a program to access any variable


outside the function.
num = 5
def myfunc1():
global num
print("Accessing num =",num)
num = 10
print("num reassigned =",num)
myfunc1()
print("Accessing num outside myfunc1",num)
Output:
Accessing num = 5 Global variable num is accessed as the ambiguity is resolved by
num reassigned = 10 prefixing global to it
Accessing num outside myfunc1 10

PYTHON STaNDaRD LIBRaRY


Built-in Python has a very extensive
standard library. It is a
Standard Library
collection of many built
Module
in functions that can be
Function
called in the program as
User Defined and when required, thus
saving programmer’s time
Figure 7.7: Types of functions of creating those commonly
used functions everytime.
Built-in functions
FUNCTIONS 163

Built-in functions are the ready-made functions in


Python that are frequently used in programs.
input(), int() and print() are the built-in
functions.

Input or Output Built-in


Datatype Functions
Mathematical Other Functions
Conversion Functions
input() bool() abs()
print() chr() divmod() len()
dict() max() range()
float() min() type()
int() pow()
list() sum()
ord()
set()
str()
tuple()

Table 7.1 Commonly used built-in functions


Function Example
Syntax Output

abs(x) >>> abs(4)


4
>>> abs(-5.7)
5.7
divmod(x,y) >>> divmod(7,2)
(3, 1)
>>> divmod(7.5,2)
(3.0, 1.5)
>>> divmod(-7,2)
(-4, 1)
max(sequence) >>> max([1,2,3,4])
or 4
max(x,y,z,...) >>> max("Sincerity")
'y' #Based on ASCII value

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

1. Module name : math


It contains different types of mathematical functions.
FUNCTIONS 165
In order to use the math module we need to import it
using the following statement:
import math

Table 7.2 Commonly used functions in math module

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

[Link](x,y) >>> [Link](10,2)


2
[Link](x,y) >>> [Link](3,2)
9.0
>>> [Link](4,2.5)
32.0
>>> [Link](6.5,2)
42.25

[Link](x) >>> [Link](144)


12.0
>>> [Link](.64)
0.8
[Link](x) >>> [Link](0)
0
>>> [Link](6)
-0.279

2. Module name : random


import random
Table 7.3 Commonly used functions in random module

Function Argument Return Example


Syntax Output
[Link]() No argument Random >>> [Link]()
(void) Real Number 0.65333522
(float) in the
range
0.0 to 1.0
FUNCTIONS 165
random.
randint(x,y) x, y are integers Random integer >>> [Link](3,7)
such that between x and y 4
x <= y >>> [Link](-3,5)
1
>>> [Link](-5,-3)
-5.0
random.
randrange(y) y is a positive integer Random integer >>> [Link](5)
signifying the stop between 0 and y 4
value
random.
randrange(x,y) x and y are positive Random integer >>> [Link](2,7)
integers signifying between x and y 2
the start and stop
value

3. Module name : statistics


:
import statistics

Table 7.4 Some of the function available through statistics module


Function Syntax Argument Return Example
Output
[Link](x) x is a numeric arithmetic >>> statistics.
sequence mean mean([11,24,32,45,51])
32.6

[Link](x) x is a numeric median >>>statistics.


sequence (middle median([11,24,32,45,51])
value) of x 32
[Link](x) x is a sequence mode >>> statistics.
(the most mode([11,24,11,45,11])
repeated 11
value) >>> statistics.
mode(("red","blue","red"))
'red'
166 COMPUTER SCIENCE – CLASS XI

Note:

• import statement can be written anywhere in the


program
• Module must be imported only once
• In order to get a list of modules available in Python, we
can use the following statement:
>>> help("module")
• To view the content of a module say math, type the
following:
>>> help("math")

2021-22
FUNCTIONS 167

Figure 7.8: Content of module "math"


• The modules in the standard library can be found in
the Lib folder of Python.
(B) From Statement
Instead of loading all the functions into memory by
importing a module, from statement can be used to
access only the required functions from a module.
Its syntax is
>>> from modulename import functionname [,
functionname,...]
To use the function when imported using "from
statement" we do not need to precede it with the module
name.

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 )

>>> a = basic_math.addnum(2,5) #Call addnum() function of the


>>> a #basic_math module
7
>>> a = basic_math.subnum(2,5) #Call subnum() function of the
>>> a #basic_ math module
-3
>>> a = basic_math.multnum(2,5) #Call multnum() function of the
>>> a #basic_math module
10
>>> a = basic_math.divnum(2,5) #Call divnum() function of the
>>> a #basic_math module
0.4
>>> a = basic_math.divnum(2,0) #Call divnum() function of the
168 COMPUTER SCIENCE – CLASS XI

Zero Divide Error #basic_math module


doc variable stores the docstring.
To display docstring of a module we
need to import the module and type the following:
print(<modulename>. doc ) # are 2 underscore without space
FUNCTIONS 169

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

2. How is [Link](89.7) different from [Link]


(89.7)?
3. Out of random() and randint(), which function
should we use to generate random numbers between
1 and 5. Justify.
4. How is built-in function pow() function different
from function [Link]() ? Explain with an
example.
5. Using an example show how a function in Python
can return multiple values.
6. Differentiate between following with the help of an
example:
a) Argument and Parameter
b) Global and Local variable
7. Does a function always return a value? Explain
with an example.
FUNCTIONS 171
2021-22
172 COMPUTER SCIENCE – CLASS XI

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:

Shopping Amount Discount Offered

>=500 and <1000 5%

>=1000 and <2000 8%

>=2000 10%

An additional discount of 5% is given to customers


who are the members of the store. Create a program
using user defined function that accepts the shopping
amount as a parameter and calculates discount and net
amount payable on the basis of the following conditions:
Net Payable Amount = Total Shopping Amount –
Discount.
3. ‘Play and learn’ strategy helps toddlers understand
concepts in a fun way. Being a senior student you
have taken responsibility to develop a program using
user defined functions to help children master two
and three-letter words using English alphabets and
addition of single digit numbers. Make sure that you
perform a careful analysis of the type of questions
that can be included as per the age and curriculum.
2021-22
172 COMPUTER SCIENCE – CLASS XI

NOtES 4. Take a look at the series below:


1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
To form the pattern, start by writing 1 and 1.
Add them together to get 2. Add the last two
numbers: 1+2 = [Link] adding the previous
two numbers to find the next number in the series.
These numbers make up the famed Fibonacci
sequence: previous two numbers are added to get
the immediate new number.
5. Create a menu driven program using user defined
functions to implement a calculator that performs
the following:
a) Basic arithmetic operations(+,-,*,/)
b) log10(x),sin(x),cos(x)

SUGGEStED LaB. ExERcISES


1. Write a program to check the divisibility of a
number by 7 that is passed as a parameter to the
user defined function.
2. Write a program that uses a user defined function
that accepts name and gender (as M for Male,
F for Female) and prefixes Mr/Ms on the basis of
the gender.
3. Write a program that has a user defined function
to accept the coefficients of a quadratic equation
in variables and calculates its determinant. For
example : if the coefficients are stored in the
variables a,b,c then calculate determinant as b2-
4ac. Write the appropriate condition to check
determinants on positive, zero and negative and
output appropriate result.
4. ABC School has allotted unique token IDs from (1
to 600) to all the parents for facilitating a lucky
draw on the day of their Annual day function. The
winner would receive a special prize. Write a
program using Python that helps to automate the
task.(Hint: use random module)
5. Write a program that implements a user defined
function that accepts Principal Amount, Rate,
Time, Number of Times the interest is
compounded to calculate and displays
compound interest. (Hint: CI=P*(1+r/n) )
nt
FUNCTIONS 173

6. Write a program that has a user defined function


to accept 2 numbers as parameters, if number 1 NOTES
is less than number 2 then numbers are swapped
and returned, i.e., number 2 is returned in place
of number1 and number 1 is reformed in place of
number 2, otherwise the same order is returned.
7. Write a program that contains user defined
functions to calculate area, perimeter or surface
area whichever is applicable for various shapes
like square, rectangle, triangle, circle and cylinder.
The user defined functions should accept the
values for calculation as parameters and the
calculated value should be returned. Import the
module and use the appropriate functions.
8. Write a program that creates a GK quiz consisting
of any five questions of your choice. The questions
should be displayed randomly. Create a user
defined function score() to calculate the score of the
quiz and another user defined function remark
(scorevalue) that accepts the final score to display
remarks as follows:
Marks Remarks
5 Outstanding
4 Excellent
3 Good
2 Read more to score more
1 Needs to take interest
0 General knowledge will always help you. Take it seriously.

CaSE STUDY-BaSED QUESTION


For the SMIS system extended in Chapter 6 let us do
the following:
1. 7.1 Convert all the functionality in Chapter 5 and 6
using user defined functions.
2. 7.2 Add another user defined function to the above
menu to check if the student has short attendance
or not. The function should accept total number of
working days in a month and check if the student
is a defaulter by calculating his or her attendance
using the formula: Count of days the student was

2021-
22
174 COMPUTER SCIENCE – CLASS XI

NOTES present or the total number of working days. In


case the attendance calculated is less than 78%, the
function should return 1 indicating short
attendance otherwise the function should return 0
indicating attendance is not short.
Let’s peer review the case studies of others based
on the parameters given under “DOCUMENTATION
TIPS” at the end of Chapter 5 and provide a feedback to
them.
FUNCTIONS 175
2021-
22

You might also like