0% found this document useful (0 votes)
36 views14 pages

CH 7 - Functions

Chapter 7 discusses functions in modular programming, defining functions, their types, and advantages. It explains user-defined functions, their syntax, and examples, as well as the differences between arguments and parameters. Additionally, it covers built-in functions, modules, and various mathematical and statistical functions available in Python, along with the use of docstrings for documentation.

Uploaded by

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

CH 7 - Functions

Chapter 7 discusses functions in modular programming, defining functions, their types, and advantages. It explains user-defined functions, their syntax, and examples, as well as the differences between arguments and parameters. Additionally, it covers built-in functions, modules, and various mathematical and statistical functions available in Python, along with the use of docstrings for documentation.

Uploaded by

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

CHAPTER-7

FUNCTIONS
1. What is modular programming?
➢ The process of dividing a computer program into separate independent
blocks of code.
➢ separate subproblems with different names and specific functionalities is
known as modular programming.

2. What is a function? What are the types of function.


➢ A function is a sub-program designed for specific purpose.
➢ It can be defined as a named group of instructions that accomplish a specific
task when it is invoked.
➢ There are two types of function:
➢ Built-in function
➢ User-defined function

3. What are the advantages of function?



Increases readability, better organized and easy to understand.

Reduce program size, therefore debugging is easier.

Increase reusability and avoid repetitions of writing the same piece of code.

Work can be easily divided among team member, so task is completed at
the earliest.
4. What is user-defined functions? Write their advantages.
➢ An used defined function is a type of function that is defined by the user
within a program.
➢ These can be customized as per the user or program requirement.
Advantages:
➢ Code reusability- user defined function can be used anywhere and any
number of times in a program.
➢ Modularity- A method of dividing a larger program into smaller
functions makes problem solving easy.
➢ Customization- Allows modifications easily, so changes can be done
depending on requirements.

Krithika Sivakumar, Department of Computer Science


5. Explain User-defined functions with syntax and an example.
➢ An used defined function is a type of function that is defined by the
user within a program.
➢ These can be customized as per the user or program requirement.
Syntax:
def function_name ([parameter1, parameter2,…..]):
Statement(s)
[return value]
To define a function, the following points needs to be checked.
• The items enclosed in “[]” are called optional parameters.
• A function header ends with a colon(:)
• A function may or may not return a value.
• Function body should be indented within the function header
• Rules for naming identifiers also applies for naming a function.
Example:
# function definition
def sum():
a=int(input(“Enter the value of a”))
b=int(input(“Enter the value of b”))
sum=a+b
print(“The sum of a and b is “,sum)
# function call
sum()

Krithika Sivakumar, Department of Computer Science


6. Differentiate between arguments and parameters.
Arguments Parameters
• They are used in function • They are used in function
call header
• A value is passed to the • A value is received in the
function header during the function header
function call
• This is also called actual • This is also called formal
parameters parameters
• Eg. • Eg.
def sum(x,y): def sum(x,y): //Parameters
z=x+y z=x+y
print(z) print(z)
sum(5,10)//arguments sum(5,10)//arguments

Note:
Memory address of both arguments and parameters are same.
Eg.

def square(n):
d=n*n
print(d)
print("The id value of n is",id(n))
num=int(input("Enter the value of num"))
square(num)
print("The id value of num is ",id(num))
Here the both the id() of num and n will return the same value.

Krithika Sivakumar, Department of Computer Science


7. Explain how to use string as a parameter with programming example.
A user defined function accept string also as an argument.

def fullname (first, last):


fullname=first + “ “ +last
print (“Hi”, fullname”)
first=input (“Enter the first name”)
last=input (“Enter the last name”)
fullname(first, last)

8. What is default parameter? Explain with an example.


➢ A default argument will take the default value if no argument value is
passed during the function call.

def sum (x, y=10):


sum=x+y
print(sum)
sum (20)
Here, the value of y will take the default value 10.
9. What are the rules/important points to remember about function?
➢ A function argument can also be an expression like avg(n1,n2+2,n3*2)
➢ The parameter should be in the same order as that of arguments
➢ The default parameters must be the trailing parameters in the function
header.
Eg.
avg(n1,n2,n3=4)
avg(n1,n2=4,n3=5)
avg(n1=10,n2,n3) # wrong

Krithika Sivakumar, Department of Computer Science


10. What is the purpose of using ‘return’ statement in function?
➢ A function may or may not return a value when called.
➢ A function which is not returning a value when it is called is void function.
➢ The reason for using return function is:
• returns the control to the calling function
• return value(s) or None.
11. What are the types of user-defined function in python.
There are four types of user defined functions, they are
• 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 with return value(s).
12. Explain flow of execution in detail.
➢ It can be defined as the order in which the statements in a program are
executed.
➢ Execution always starts with the first statement in the program.
➢ It is executed from top to bottom.
➢ Function definitions don’t change the flow of execution, but statements
inside the function are only executed when the function is called.
➢ When the interpreter encounters the function call, the control flow jumps
to the function body and executes all the statement and returns back to the
function call.
➢ Then it will execute the remaining statements in a program.
Example:
4
def area (l,b):
5 return l*b
1 l=int (input (“Enter the length”))
2
b=int (input (“Enter the breadth”))
3,6 area=area (l, b)
7 print(area)

Krithika Sivakumar, Department of Computer Science


13. Explain scope of variables with an example.
➢ The scope of variables depends on the place where the variable is
defined.
➢ There are two types of variable scope.
• Global scope/variable- A variable that is defined outside any
function is known as global variable.
• Any changes made to the global variable will impact all the
functions in the program.
• Local scope/variable- A variable that is defined inside any
function is called local variable.
• It can be accessed only inside the function so it has a limited
scope.

def square(n):
d=n*n
print(d)
num=int(input("Enter the value of num"))
square(num)

Note:
Here, d and n are local variables
Num is a global variable.
Note:
➢ When local variable and global variable is same name, then it is
considered local variable to that function and hides the global variable.
➢ If we want to modify the local variable to global variable, then the
keyword ‘global’ should be prefixed to the variable name in the
function.

Krithika Sivakumar, Department of Computer Science


14. Explain the classification of functions.
➢ The functions in python are broadly classified into two types.
• Standard Library functions
• User defined functions
Standard Library Function:
➢ There are two standard library functions, called built-in functions and
modules.
• Built-in Functions:
These are pre-defined functions that are always readily available
for use. This is the part of the python interpreter.
E.g. input (), int (), print ().

• User defined functions:


Check the answer above.
15. What is module in python programming? Explain how to import and
used them in program.
➢ Function is a grouping of instructions.
➢ A module is a grouping of functions.
➢ A module is a file containing python definition and statements.
➢ It is a way of organizing and reusing of codes.
➢ It is a (.py) file containing executable code as well as function definition.
➢ We can import the module into other modules using the import
statement.
➢ Once we import, we can use all the functions directly.
➢ Syntax:
import modulename1[,modulename2,…]
To call the specific function from the module,we can use(. dot)
operator.
modulename. functionname()
Example:
import math
[Link](x)

Krithika Sivakumar, Department of Computer Science


16. What are the most commonly used built-in modules?
➢ math
➢ random
➢ statistics

17. What are the most commonly used built-in functions?


➢ abs(x):
x may be an integer or floating-point number, it returns Absolute value
of x.
Example- abs(-4)=4

➢ divmod(x,y):
x and y are integers, it returns a tuple: (quotient, remainder)
Example: divmod(7,2) = (3, 1)

➢ max(sequence) or max(x,y,z,...):
x,y,z may be integer or floating point number. It returns a largest
number in the sequence/ largest of two or more arguments.
Example: max([1,2,3,4])=4
➢ pow(x,y[,z]):
x,y,z may be integer or floating point. It returns xy (x raised to the power
y) if z is provided, then: (xy ) % z
Example: pow(5,2,4)=1
➢ sum(x[,num]):
x is a numeric sequence and num is an optional argument, It returns sum of
all the elements in the sequence from left to right.
Example: sum([1,2,3],4)=10

➢ len(x):
x can be a sequence or a dictionary, it returns count of elements in x.
Example: len(“welcome”)=7

Krithika Sivakumar, Department of Computer Science


18. Explain any five functions of math module with example.
➢ Module name: math
➢ It contains different types of mathematical functions.
➢ Most of the functions in this module return a float value.
➢ Python is case sensitive. All the module names are in lowercase.
➢ Some of the commonly used functions are.
➢ math. ceil(x):
• x may be an integer or f loating point number. It returns ceiling
value of x.
Example: [Link] (9.7) = 10
➢ [Link](x):
• x may be an integer or f loating point number and it returns
f loor value of x.
Example: [Link](4.5)=4
➢ [Link](x):
• x may be an integer or floating-point number and it returns
absolute value of x.
Example: [Link] (-6.7) = 6.7
➢ [Link](x):
• x is a positive integer and it returns factorial of x.
Example: [Link] (5) =120
➢ [Link](x,y):
• x and y may be an integer or floating point and it returns x % y
with sign of x.
Example: [Link] (4,4.9) =4.0
➢ [Link](x,y):
• x, y are positive integers and it returns gcd (greatest common
divisor) of x and y.
Example: [Link](10,2)=2

Krithika Sivakumar, Department of Computer Science


➢ [Link](x,y):
• x, y may be an integer or f loating point number and it returns xy
(x raised to the power y).
Example: [Link] (3,2)=9.0
➢ [Link](x):
• x may be a positive integer or floating point number and it returns
square root of x.
Example: [Link](144)=12
➢ [Link](x):
• x may be an integer or f loating point number in radians and it
returns sin of x in radians.
Example: [Link](6)=0
19. Explain functions of random module with example.
➢ This module contains functions that are used for generating random
numbers.
➢ We can import by using the statement - import random.
➢ Some of the commonly used functions are.

➢ [Link]():
• it will not accept any argument, and it returns real numbers in the
range 0.0 to 1.0.
Example: [Link]()=0.66666
➢ random. randint(x,y):
• x, y are integers such that x <= y, and it returns Random integer
between x and y.
Example: [Link](-3,5) =1
➢ random. randrange(y):
• y is a positive integer signifying the stop value and it returns
random integer between 0 and y.
Example: [Link](5)=4

Krithika Sivakumar, Department of Computer Science


➢ random. randrange(x,y):
• x and y are positive integers signifying the start and stop value.
random integer between x and y.
Example: [Link](2,7)=2
20. Explain functions of statistics module with example.
➢ This module provides functions for calculating statistics of numeric (Real-
valued) data.
➢ We can import by using the statement - import random
import statistics.
➢ Some of the commonly used functions are.
➢ [Link](x):
• x is a numeric sequence, and it returns sequence arithmetic mean.
Example: statistics. mean([11,24,32,45,51]) =32.6
➢ [Link](x):
• x is a numeric sequence and it returns median (middle value) of x.
Example: statistics. median ([11,24,32,45,51]) =32
➢ [Link](x):
• x is a sequence and it returns mode (the most repeated value).
Example: statistics. mode([11,24,11,45,11])= 11
21. Explain module in python
➢ 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").
➢ The modules in the standard library can be found in the Lib folder of Python.

Krithika Sivakumar, Department of Computer Science


22. What is the use of ‘from’ statement in python? Give an example.
➢ If you import a module, usually all the functions in the module will be loaded
into the memory.
➢ By using ‘from’ statement ,it loads only the specified function(s) in the
memory.
➢ Syntax: from modulename import functionname [, functionname,...]
➢ Example :
from math import sqrt
value = 144
sqrt(value)=12

23. What is composition? Give an example.


➢ A programming statement wherein the functions or expressions are
dependent on each other’s execution for achieving an output is termed as
composition.
➢ Example:
from math import ceil,sqrt
value = ceil(143.7)
sqrt(value) =12
➢ The execution of the function sqrt() is dependent on the output of ceil()
function.

24. What is ‘Docstring’ in python?


➢ It is also called python documentation strings.
➢ It is a multiline comment that is added to describe the modules, functions etc.
➢ They usually added in the first line using (‘’’) triple quotes.
➢ Example:
‘’’ This is a
Python user defined module’’’.

Krithika Sivakumar, Department of Computer Science


25. How to create user defined module, Explain with an example.
➢ 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.
➢ 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.
Example:
basic_math Module
*******************
‘’’This module contains basic arithmetic operations that can be carried out
on numbers’’’

'''This module contains basic arithmetic operations


that can be carried out on numbers'''
#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)

Krithika Sivakumar, Department of Computer Science


Output:
import basic_math
a=basic_math.addnum(2,5)
a
7
a=basic_math.subnum(2,5)
a
-3
a=basic_math.multnum(2,5)
a
10
a=basic_math.divnum(2,5)
a
0.4

26. List out other built-in functions in python.

Krithika Sivakumar, Department of Computer Science

You might also like