0% found this document useful (0 votes)
6 views16 pages

Functions

The document outlines the importance of functions in Python, detailing their types, including built-in functions, module functions, and user-defined functions. It explains how to define and call functions, the concept of parameters, and the differences between local and global scope. Additionally, it covers recursion, its advantages and disadvantages, and provides examples of various function types and their usage.

Uploaded by

dhruvsuyal57
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
6 views16 pages

Functions

The document outlines the importance of functions in Python, detailing their types, including built-in functions, module functions, and user-defined functions. It explains how to define and call functions, the concept of parameters, and the differences between local and global scope. Additionally, it covers recursion, its advantages and disadvantages, and provides examples of various function types and their usage.

Uploaded by

dhruvsuyal57
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 16

DOON INTERNATIONAL SCHOOL

CITY CAMPUS,
DALANWALA, DEHRADUN

NOTE: Weightage of the chapter in board’s exam is more than 10 Marks


 Three Output Questions ( 2 Marks + 3 Marks + 2 Marks)
 One theory question of 2 Marks with Syntax and Example.
 In all other programming questions you are required to write
function ONLY (not the complete programme)

Learning Outcomes: Understand the concept of functions in Python.


Definition: A function is a group of statements that exists within a program for the
purpose of performing a specific task. Instead of witting a large program as one long
sequence of instructions, it can be written as several small functions, each performing a
specific part of the task. They constitute line of code(s) that are executed sequentially
from top to bottom by Python Interpreter.
Types of Functions:
There are three types of functions in python:
1.Built In Function(Library Functions): These functions are already built in the python
library. Example : type( ), len( ), input( )
2. Functions in modules: A module is a file containing functions and variables defined
in separate files. A module is simply a file that contains python code or a series of
instructions. Module also make it easier to reuse the same code in more than on program.
If we have written a set of functions that is needed in several different programs, we can
place those functions in a module, then we can import module in each program that needs
to call one of the functions.

Python language provide two important methods to import modules in a program which

1
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

are as follows:-
i. import statement- to import entire module
ii. from- to import all functions or selected ones
iii. import- to use modules in a program, we import them using the import statement

Functions of math module:


To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49) 7.0

2 ceil( ) Returns the upper integer >>>math.ceil(s81.3


) 82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668

Function in random module:


randrange( ) : This method generates an integer between its lower and upper argument. By
default, the lower argument is 0 and upper argument is 1.
Example:- >>> import. randrange(30)
This line of code shall generate any random number between 0 to 29 .
random( ) : This function generates a random number from 0 to 1 such as 0.546723. this
function can be used to generate random floating point values. It takes no parameter and
returns values uniformly between 0 and 1( including 0, but excluding1)
Example:
>>> import random
>>>print(“The random number is:=”,random.random( )
The random number is:= 0.299494
Note: it can print any fractional number between 0 to less than 1

randint( )- This function generates the random integer values including two given numbers
(start and end values).
Syntax: randint(start, end)
It has two parameters. Both parameters must have integer values.
Example: import random n=random.randint(3,7)
It can generate number from 3 to 7 any one and will store in n.
Example2: What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the maximum values the
can be assigned to each of the variables FROM and TO. (CBSE Sample paper 2020)

import random
2
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

Ar = [ 20, 30, 40, 50, 60, 70]


FROM =random.randint(1,3)
TO= random.randint(2,4)
for k in range (FROM, TO+1)
print(Ar[k], end=”#”)

Possible output:- 1) 10#40#70# 2) 30#40#50#


2) 50#60#70# 3) 40#50#70#

Ans. 2) 30#40#50
Maximum Value of FROM, TO is 3, 4

User Defined Functions: The functions those are defined by the user are called user
defined functions.
User defined functions:
The syntax to define a function is:
def function-name ( parameters) :
#statement(s)
Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python. Parameters (arguments) through which we pass values to a
function. They are ptional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements must
have same indentation level. An optional return statement to return a value from the
function.
Example:
def display(name):
print("Hello " + name + " How are you?")

Function Parameters:
Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
Actual Parameter(Arguments): When a function is called, the values that are
passed in the call are called actual parameters. At the time of the call each actual
parameter is assigned to the corresponding formal parameter in the function
definition.
There are four different types of Actual Parameters(arguments) are available
in Python:
Default Parameters: Python allows function arguments to have default values.
If the function is called without the argument, the argument gets its default
value.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters z=x+y
3
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Positional Argumets:
Position-only arguments mean whenever we pass the arguments in the order we have
defined function parameters in which if you change the argument position then you
may get the unexpected output. We should use positional Arguments whenever we
know the order of argument to be passed.
Example:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge(name="NS", age=75)
nameAge(age=14, name="Apoorva")

Keyword Arguments:
Keyword-only arguments mean whenever we pass the arguments(or value) by their
parameter names at the time of calling the function in Python in which if you
change the position of arguments then there will be no change in the output.

Variable Length Argumets:


Variable-length arguments, abbreviated as varargs, are defined as arguments that
can also accept an unlimited amount of data as input. The developer doesn't have
to wrap the data in a list or any other sequence while using them.
There are two types of variable-length arguments in Python-
Non - Keyworded Arguments denoted as (*args)
Keyworded Arguments denoted as (**kwargs)

Calling the function:


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.
Syntax:
function-name(parameters)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0

The return statement:


The return statement is used to exit a function and go back to the place from where it was
called. There are two types of functions according to return statement:
a. Function returning some value
b. Function not returning any value
4
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

a. Functionreturning some value :


Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2 Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple print(S)
OUTPUT: (7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately print(s1, s2, s3)
OUTPUT:
7 7 11

b.Function not returning any value : The function that performs some operations
but does not return any value, called void function.
def message():
print("Hello")

m=message() print(m) OUTPUT: Hello


None
Note:- A function may or may not return a value. If function is not returning any value
then it this type function is known as void function and it returns a legal vale None
SCOPE AND LIFETIME OF VARIABLES:
Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence,
they have a local scope.
There are two types of scope for variables:
i) Local Scope
ii) Global Scope
Local Scope: Variable used inside the function. It cannot be accessed outside the
function. In this scope, the lifetime of variables inside a function is as long as the
function executes. They are destroyed once we return from the function. Hence, a
function does not remember the value of a variable from its previous calls.
Global Scope: Variable can be accessed outside the function. In this scope, Lifetime
of a variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
5
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

print("Value outside function:",x)


OUTPUT:
Value inside function: 10 Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function
my_func()changed the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function)
from the one outside. Although they have same names, they are two different
variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a
global scope. We can read these values from inside the function but cannot change
(write) them. In order to modify the value of variables outside the function, they must
be declared as global variables using the keyword global.
MAIN( ) AS A FUNCTION: Including a main( ) function is not mandatory in Python. It
can structure our Python program in a logical way the puts the most important components of
the program into one function. It can also make our programs easier for non-python
programmers to read.
Example:- def DIS ( )
for i in range(1,11):
print(2 * i)
def main( ):
print(“Table of 2”)
DIS( )
In the above example, we have called the main( ) explicitly either from the shell or from the
script after giving the calling function for main( ) function in the end.

RECURSION: Recursion is one of the most powerful tools in a programming language. It is


a function calling itself again and again. Recursion is defined as defining anything in terms of
itself. In other words, it is a method in which a function calls itself one or more times in its
body.
HOW RECURSION WORKS: There must be a terminating condition for the problem
which we went to solve with recursion. This condition is called the base case for that
problem.There must be an if condition in the recursive routine. This if clause specifies the
terminating condition of the recursion.
Reversal in the order of execution is the characteristics of every recursive problem, i.e. when
a recursive program is taken for execution, the recursive function calls are not executed
immediately. They are pushed on to stack as long as the terminating condition is encountered.
As soon as the recursive condition is encountered, the recursive calls which were pushed on
to stack are removed in reverse order and executed one by one. It means that the last call
made will execute first, then the second-last call will execute and so on until the stack is
empty. This condition is called recursive case.

Example:- def power(n, s):


if n== 0:
return 1
else:
return n* power(n,s-1)
6
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

r=2
print( power(2,4))

Explanation:- In each call, the power function passes the actual parameters to the version
being called. The value of n is same for each power function call, but the value of s is
decremented by 1 for each call until s becomes 0. When s becomes 0, the function power( )
starts returning a value of n.
So answer will be 16

DISADVANTAGES OF USING RECUSRION:- It consume more storage space because


the recursive calls along with local variables are stored on the stack. The computer may run
out of memory if the recursive calls are not checked. Most important it is less efficient in
terms of speed and execution time.

POINTS TO REMEMBER:
 A module is separately saved unit whose functionality can be reused in any
other program.
 A function is a named block of statements that can be invoked by its name.
 Python can have three types of functions:-
1. Built in function
2. Function in Modules
3. User –Defined functions
 A python module has the .py extension
 There are two forms of importing Python module statements:
1. import <module names>
2. from <module> import <object>
 Functions make program handling easier as only a small part of the program is
dealt with at a time, there by avoiding ambiguity.
 Keyword arguments are the named arguments with assigned values being
passed in the function –call statement.
 A function may or may not return a value.
 A void function internally returns legal value None.
 The program part(s) in which a particular piece of code or a data value(e.g.
variable) can be accessed is known as Variable Scope.
 A local variable having the same name as that of a global variable hides the
global variables in its function.
 A function is said to be recursive if it calls itself.
 There are two cases in each recursive functions – the recursive case and base
case.
Short Answer Type Questions (1-Mark)
Q1. What is function?
Ans: A function in Python is a named block of statements within a program .That can be
invoked in any other part of the program.

Q2. What is an argument?

7
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

Ans. An argument is data passed to a function through function call statement, for example
in the statement print (math.sqrt(64)) the integer 64 is an argument.

Q3. What is default parameter?


Ans: A parameter having default value in the function header is known as a default
parameter.

Q4. What is function module?


Ans. A “module” is a chunk of Python code that exists in its own(.py) file and is intended to
be used by Python code outside itself. The modules can be “imported” in other programs so
the functions and other definitions in imported modules become available to code that
imports them.

Q5. What is the difference between Local variable and Global Variable?
Ans. Local Variable:- It is a variable which is declared within a function or within a block. It is
accessible only within a function/block of a program
Global Variable: It is a variable which is declared outside all the function. It is accessible
throughout the program .

Q6.What is recursion function?


Ans:- In a program, if a function calls itself (whether directly or indirectly), it is known as
recursion function.

Q7. What are base case and recursive case? What is their role in recursive function?
Ans. In a recursive solution, the base cases are predetermined solutions for the simplest
version of the problem. If the given problem is a base case, no further computation is
necessary to get the result. The recursive case is the one that calls the function again with a
new set of values. The recursive step is a set of rules that eventually reduces all versions of
the problem to one of the base cases when applied repeatedly.

Q8. Rewrite the correct code after removing the errors: -


def SI(p,t=2,r):
return (p*r*t)/100
Ans: - def SI(p, r, t=2):

return(p*r*t)/100

Q9. Consider the following function headers. Identify the correct


statement: -
1) def correct(a=1,b=2,c): 2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3): 4) def correct(a=1,b,c):
Ans: - 3) def correct(a=1,b=2,c=3)

Q10.What will be the output of the following code?


8
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
a=1
def f():
a=10
print(a)
Ans: The code will print 1 to the console.

Q11. Find and write the output of the following python code:
x=”abcdef”
i=”a”
while i in x:
print(i, end=” “)
Ans:- Answer is infinite time aaaaaaaaa…….

Q12. Find and write the output of the following python code:
a=10
def call( ):
global a
a=15
b=20
print(a)
call( )

Ans:- 15

Q13. Find and write the output of the following python code:

x=10
y=0
while x>y:
print(x,y)
x=x-1
y=y-1

Ans.: 10 0
9 1
8 2
7 3
6 4

Application Based Questions ( 3 Marks)

Q1. Write a python program to sum the sequence given below. Take the input n from the
user.

Solution:
def fact(x):
j=1 , res=1
9
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)

Q2.Write a recursive function print factorial of a non-negative number.


def fact( x):
if x<=1:
return x
else:
return x * fact(x-1)
Q3. Write a program to have following functions:
i. a function that takes a number as argument and calculates cube for it. The function
does not return a value. If there is no value passed to the function in function call,
the function should calculate cube of 2.
ii. a function that takes two char argument and returns True if both the arguments are
equal otherwise false.
def cube( x=2):
print( x* * 3)

def compare(a, b):


return a==b:

cube (5) # when value is passed


cube( ) # when value is not passed
print(compare(‘x’, ‘x’)) # when both character are same
print(compare(‘x’, ‘r’)) # when both character are not same

Q4. Write a function to sum all the numbers in a list.


def add( x): # x is a list of integer numbers
total =0
for i in range(0, len(x)):
total = total +x[i]
print ( total)
List=[ ]
N=int(input(“Enter How many Numbers”))
for i in range(0, N):
Num=int(input(“Enter number”))
List.append(Num )
Add(List)
10
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

Q5. Find out option which is not possible from the following program:

import random
x=3
n=random.randint(0,x)
for i in range(n):
print(i, "#",i+1, end=" ")
i. 0 # 1 ii. 1 # 2 iii. 2 # 3 iv.3 # 4
Ans. Option iv. 3 # 4 is not possible.

Q6. Find and write the output of the following python code:

import random
Go = random.randint(0,3)
X= [100, 75, 10, 125]
for i in range( Go):
print(X[i], “$$”, end=” “)
i.100$$75$$10$$, ii.75$$10$$125$$, iii. 75$$10$$, iv.10$$125&&100

Ans. Option (i) 100$$75$$10$$ is possible

Q7. Find and write the output of the following python code:
def DISXII(s):
str2 = " "
for i in range (len(s)):
if s[i] not in "aeiouAEIOU":
str2=str2+s[i]
print(s)
print(str2)

str="Hello How Are You"


DISXII(str)
print(str)
print(str2)

Ans:- Hello How Are You


Hll Hw r Y
Hello How Are You
Q8. Find and write the output of the following python code:
def Func( x, y=5):
if x%y==0:
retun x+1
else:
return y-1
11
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

P=20
Q=21
Q=func(P,Q)
print(P,Q)
P=func(Q)
print(P,Q)
Q=Func(P)
print(P,Q)

Ans:- 20 20
14 20
14 14
Q9. Find and write the output of the following python code:
def Check(N1=1, N2=2):
N1=n1 + n2
N2= N2+1
print(N1, N2)
Check( )
Check(2, 1)
Check(3)

Ans. 33
32
53

Q10. Find and write the output of the following python code:
def Exec(B, C=100):
Temp = B + C
B= B + Temp
If c = = 100:
print(Temp, B, C)
M= 90
N= 10
Exec(M)
print(M, N)
Exec(M,N)
print(M, N)

Ans: 190 280 100


90 10
90 10

Q11. Find and write the output of the following python code:

12
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

def DIS( ):
R= 1
Num= 65
while R < = 5:
J= 1
while J<=R:
print(chr(num), end=” “)
J=J+1
Num= Num + 1
print( )
R = R+1
DIS( )

Ans: A
BC
DEF
GHIJ
KLMNO

Q12. Write a program to enter a number and using function print its factorial.
def Factorial(x):
F=1
while x > 0:
F=F*x
x=x–1
print(“factorial of entered number=”, F)

Num=int(input(“enter number for factorial”))


Factorial(Num)

Q13. Write a function which will accept a string as argument and find out it is Palindrome or
not.

Ans. def Palindrome( Str):


int L = len(Str)
S=“ “
for K in range (L-1, -1, -1):
S= S + [ K ]
if Str= =S:
print(“ It is Palindrome”)
else:
print(“ It is Not Palindrome”)

St =input(“Enter String”)
Palindrome(St)
13
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

Q14. Write a function which will accept a List and reverse the List without using reverse.
Ans: def Rev(Lst):
F=0
R=len(Lst)-1
while F < R:
Temp = Lst[F]
Lst[F] = Lst[R]
Lst[R] = Temp
F=F+1
R=R–1
print(Lst)

Q15. Write definition of functionEvenSum(List, N) to add all even numbers of a list


where parameters are List, N ( length of the list)
Ans. def EvenSum(List, N):
Total=0
for R in range(0,N):
if List[R]% 2 ==0:
Total = Total +List[R]
print( Total{

Q16. Write a function in Python Reverse(X), which will print all elements of list X in reverse
order after multiplying by 4 .
Example:- 2 5 12 4 8 10
Then output will be like: 40 32 16 48 20 8
Ans:- def Reverse( X):
for K in range(len(X)-1,-1,-1):
print(X[i] *4,end = “ “)

Q17. Write a user defined function which will accept an integer list and its length and an
element as parameter and print “Found” with its location if element is available
otherwise print “Not Found”.
Ans:- def DIS( List, R,ele):
C= -1
for I in range (0, R):
if List[I]==ele:
C=I
if C== -1 :
print(Not Found”)
else:
print(“Found at = “,C)

Q18. Write a user defined function which will accept an integer list and its length as
parameter and delete each negative numbers from the list.
Ans:- def DELNEGATIVE(X, R):
K=0
while K <R:
14
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

if X[K]<0:
del X[K]
R=R-1
print(“List after deletion=”,X)

UNSOLVED QUESTIONS:

A. FILL IN THE BLANKS:-


i. A set of instructions/operations which is part of the program and can be
executed independently is called a ____________.
ii. Python passes parameters by ____________.
iii.The variable declared outside all the function is called a _____________.
iv.The first line of function definition is called______________.
v. A function is said to be _________________ if it calls itself.

B. MULTIPLE CHOICE QUESTIONS(MCQs):-


i. A function in Python begins with which keyword?
a. void b. return c. int d.def
ii. Name the statement that sends back a value from a function.
a. print b.input c.return d. None
iii. A variable created or defined within a function body is classified as:
a.local b.global c.built-in d.instance
iv. Which values are used by the functions to communicate information back to
the caller?
a.local b.glabal c.return d.random
v. Function that do not return any value are known as:-
a. fruitful function b.void function c.library function
d. user- defined function.

C. SHORT ANSWERS:
i. A program having multiple functions is considered better designed than a program
without any function. Why?
ii. Describe the different types of functions in Python using appropriate examples.
iii. What is the difference between local and global variables?
iv. Differentiate between random.random( ) function and random.randint() function.
v. What do you mean by Lifetime of a variable?
vi. When function returns None in Python program?
vii. Write a Python function that takes a number as a parameter and checks whether
number is prime or not.
viii. Write a function that takes a List as a parameter and return greatest number.
CBSE BOARD 2013
ix. Write a function that takes a String as a parameter and print at first vowels then
print all consonants.
x. Write a function that takes a List as a parameter and Write a user-defined function
NoTwoThree(LIST,N) where N is length of list ,which should display the value of
all such elements and Their corresponding locations in the List (i.e the List index),

15
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

which Are not multiples of 2 or 3. N represents the total number of elements in the
List, to be checked. Example: if the List contains 1 2 3 4 25 8 12 49 9
Then the function should display the output as:
25 at location 0
49 at location 3 CBSE BOARD 2019

xi. Write the definition of a function SumEO(VALUES[ ],N) in Python, where


VALUES is a list and N is length, which should display the sum of even
values and sum of odd values of the VALUES
separately. Example: if the array VALUES contains 25 20 22 21 53
Then the functions should display the output as:
Sum of even values = 42 (i.e 20+22)
Sum of odd values = 99 (i.e 25+21+53) CBSE BOARD 2018

xii. Write a function which will accept an integer list and its size as parameter and
exchange first half elements of list with second half elements assuming list is
having even number of elements.

xiii. Write a function which will accept an integer list and its size as parameter and
shift the negative numbers to right and the positive numbers to left so that the
resultant list looks like:
Original List : [ -12, 11, -13, -5, 6, -7, 5, -3, -6]
Output List :[11, 6, 5, -12, -13, -7, -3, -6]

xiv. A List Num contains the following elements:


3, 25, 13, 6, 35, 8, 14, 45
Write a function to swap the content with next value divisible by 5 so that the
resultant list looks like:-
25, 3, 13, 35, 6, 8, 45, 14

xv. Write a function which will accept a list and its size as parameter and print sum of
all numbers which are ending with 3. Ensure that the function is able to handle
various situations viz. , list containing numbers and strings.
e.g. List[ 33, 13, “RAM”, “AYUSH”, 92, 3, “RASHMI”, 12]

output will be: 49

16

You might also like