0% found this document useful (0 votes)
86 views7 pages

CH 2

Modularity involves partitioning a program into individual components or modules. A Python module can contain objects like functions, variables, classes, etc. Functions are named blocks of code that perform tasks. There are built-in, module, and user-defined functions. Functions allow code reusability and improve program structure. Functions are defined using the def keyword and can take in parameters. The return statement exits a function optionally returning a value.

Uploaded by

Vatsal Solanki
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)
86 views7 pages

CH 2

Modularity involves partitioning a program into individual components or modules. A Python module can contain objects like functions, variables, classes, etc. Functions are named blocks of code that perform tasks. There are built-in, module, and user-defined functions. Functions allow code reusability and improve program structure. Functions are defined using the def keyword and can take in parameters. The return statement exits a function optionally returning a value.

Uploaded by

Vatsal Solanki
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
You are on page 1/ 7

FUNCTIONS

Notes

• The act of partitioning a program into individual components is called "Modularity".


• A module is a separately saved unit whose functionality can be reused.
• A Python module has the .py extension.
• A Python module can contain objects like docstrings, variables, constants, classes,
objects, statements, functions etc.
• The Python modules that come preloaded with Python are called "standard library
modules".
• A function is a named block of statements that can be invoked by its name.
• Python can have three types of functions i.e., built-in functions, functions in
modules and user-defined functions
• The docstrings are useful for documentation purpose.
• Python module can be imported in a program using import statement.
• There are two forms of import statements:
(i) import <module name>
(ii) from <module name> import <object>
• The built-in functions of Python are always available, one needs not import any
module for them.
• The math module of Python provides mathematical functionality.
• sys.stdin is the most widely used method to read input from the command line or
terminal.
• The command line sys.argv arguments is another way that we can grab input, and
environment be used from within our programs.
• The basic I/O (Input/Output) functions are input() and print() respectively.
43
• One of the most useful tools available in Python is the print() function. This simply
allows the program to display or print data for the user to read. For example:
red='Hi, how are you?"
print (red)
Output : Hi, how are you?
• Python has an input function which lets you ask a user for some text input. In
Python 2, you have a built-in function raw_input(), whereas in Python 3, you have
input() for inputting by user. The syntax is:
mydata = ninput("Prompt:')
print(mydata)
Output: Prompt:
• In Python, a number mathematical operations can be performed with ease by
importing a module named "math" which defines various functions which makes
our task easier.
o ceil(x): Returns the ceiling of x as a float, the smallest integer value greater
than or equal to x.
o floor(x): Returns floor of x as a float, the largest integer value less than or
equal to x.
o fabs(x): Returns the floating point absolute value of x.
• exp(x): Return e**x
• log(x,(base)): With one argument, returns the natural logarithm of x (to base e).

With two arguments, returns the logarithm of x to the given base calculate as
log(x)log(base)
• log10(x): Returns the base-10 logarithm of x. This is usually more accurate than
log(x,10).
• pow(x, y): Returns x raised to the power y. In particular, pow(10, x) and pow(x,
0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite,
x is negative, and y is not an integer then pow(x, y) is undefined, and raises
ValueError.
• sqrt(x): Returns the square root of x.
• cos(x): Returns the cosine of x radians.
• sin(x): Returns the sine of x radians.
• tan(x): Returns the tangent of x radians.
• degrees(x): Converts angle x from radians to degrees.
• radians(x): Converts angle x from degrees to radians.
• A function is a block of organized and reusable code that is used to perform a
single, related action. Functions provide better modularity for your application and
a high degree of code reusability.
• Function blocks begin with the keyword def followed by the function name and
parentheses ().
• Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement-the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exit a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
• Defining a function only gives a name, specifies the parameters that are to be
included in the function, a structure the blocks of code.
• The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python :
44
1. Global variables
2. Local variables
• Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.

• Built-in These are the functions that are always available in Python and can be
accessed by a programmer without importing any module.
• Examples of Some Built-in Functions
(i) print(): It prints objects to the text stream file.
(ii) input(): It reads the input, converts it to a string and returns that.
(iii) sorted(): Returns a new sorted list from the items in iterable..
(iv) bool(): Returns a boolean value i.e., True or False..
(v) min(): Returns the smallest of two or more arguments.
(vi) any(): Returns True if any element of the iterable is True.

• String Functions
(i) partition(): It splits the string at the first occurrence of the given argument
and returns a tuple containing three parts.
(ii) join(): It takes a list of string and joins them as a regular string.
(iii) split(): It splits the whole string into the items with separator as a delimeter.
• Modules: It is a file containing Python definitions and statements. We need to
import modules use any containing part before separator, separator parameter
and part after the separator if the separator parameter is found in the string of its
function or variable in our code.
• Examples of Some Module Functions
(i) fabs(): It returns the absolute value of a number.
(ii) factorial(): This method finds the factorial of a positive integer.
(iii) random(): It produces an integer between the limit arguments.
(iv) today(): This method returns the current date and time.
(v) search(): This function searches the pattern inside the string.
(vi) capitalize(): It returns the copy of string in capital letters.

• User-Defined Functions: User defined functions are those that we define ourselves
in our program and then call them wherever we want.
• Parameters: These are the values provided in the parentheses in the function
header when we define the function
• Arguments: These are the values provided in function call/invoke statement.
• Function Arguments: You can call a function by using the following types of formal
arguments:
o Required arguments/Positional arguments
o Keyword arguments
o Default arguments
o Variable-length arguments

• Required arguments are the arguments passed to a function in correct positional


order.
• Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
• A default argument is an argument that assumes a default value, if a value is not
provided in the function call for that argument.
• All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable or the scope of variable.
45
Passing different objects as an arguments :
You can send any data types of argument to a function as string, number, list,
dictionary etc., and it will be treated as the same data type inside a function.

e.g. List as an argument


def fun(Fruit):
for i in Fruit:
print(i)

Food ["Mango", "Cherry", "Grapes", "Banana"]


fun(Food)

Output:-
Mango
Cherry
Grapes
Banana

Short Answer Type Questions – (1 mark for correct answer)


Q.1 Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Q.2. What do you mean by modularity?
Q.3. What is a function call?
Q.4. Name the three categories of functions.
Q.5. What is the role of an argument of a function?
Q.6. What are docstrings?
Q.7. What are docstring conventions?
Q.8. What is the use of following functions?
Q.9. Name the constant available in math module.
Q.10. Write two ways in which you are able to use constant pi in your programs.
Q.11. What is dot notation?
Q.12. What is a function?
Q.13. What is an argument?
Q.14. What is the general syntax for defining a function in Python?
Q.15. What is function header?
Q.16. What are parameters?
Q.17. The convention for indentation within a block is four spaces. Is it true?
Q.18. Find the error in the following codes.
def minus(total_decrement)
output= total_decrement
Q. 19. What is _main_?
Q. 20. What is _name_?
Q. 21. What is the difference between arguments and parameters?
Q. 22. Name two types of function in Python.
Q. 23. Trace the flow of execution for following program.
1 def power (b,p):
2 r = b**p
46
3 return r
4
5 def calcsquare(a):
6 a= power(a,2)
7 return a
8
9 n=5
10 result = calcsquare(n)
11 print(result)
Q. 24. What will be the output of the following code?
def addEm(x,y,z):
print(x+y+z)

def prod(x,y,z):
return x*y*z

a= addEm(6,16,26)
b= prod(2,3,6)
print(a,b)
Q.25. What is the use of return statement?

Short Long Answer Type Questions - (2 mark for correct answer)


Q. 1. Find and write the output of the following Python code:
def fun(s):
k= len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
Q. 2. What do you understand by local and global scope of variables? How can you
access a global variable inside the function, if function has a variable with same
name.
Q. 3. What are the differences between parameters and arguments?
Q. 4. What are default arguments?

Q. 5. What are keyword arguments?


Q. 6. What are the advantages of keyword arguments?
Q. 7. Write a generator function generatesq () that displays the square roots of
numbers from 100 to n where n is passed as an argument.
Q. 8. What are the advantages of dividing a program into modules.
Q. 9. Differentiate between Built-in functions and user defined functions.
Q. 10. Differentiate between Built-in functions and functions defined in modules.

Long Answer Type Questions - (3 mark for correct answer)


Q. 1. List a type of arguments and explain any 2 type of arguments.
Q. 2. Write a method in Python to find and display the prime number between 2 to
N. Pass N as argument to the method.
47
Q. 3. Write a program that uses a function which take two string arguments and
returns the string comparison result of the two passed strings.
Q. 4. Write definition of a function
1. OddSum(Numbers) to add Odd values in the list Numbers.
2. EvenSum(Numbers) to add Even values in the list Numbers.
Q.5. Define a function overlapping () that takes two lists and returns true if they have
at least one member in common, False otherwise.
Q.6. Write a program for nth multiple of Fibonacci Series. Also show proper
documentation.
Q. 7. Write a Python program to reverse a string.
Q.8. A function checkMain() defined in module Allchecks.py is being used in two
different programs
In program 1 as
Allchecks.checkMain(3,'A')
and in program 2 as
checkMain(4,'Z').
Why are the functions call statements different in each program?
Q. 9. Write a python program to find simple interest using a user defined function
with parameters and with return value.
Q. 10. Explain any three string functions with example?

Case Base Questions - (5 mark for correct answer)

Q. 1. Kids Elementary is a playway school that focuses on 'Play and learn' strategy
that helps toddlers understand concepts in a fun way. Being a senior programmer,
you have taken responsibility to develop a program using user-defined functions to
help children differentiate between upper case and lower case letters/English
alphabet in a given sentence. Make sure that you perform a careful analysis of the
type of alphabets and sentences that can be included as per age and curriculum.

Write a Python program that accepts a string and calculates the number of upper
case letters and lower case letters.

Q. 2. Traffic accidents occur due to various reasons. While problems with roads or
inadequate safety facilities lead to some accidents, majority of the accidents are
caused by drivers' carelessness and their failure to abide by traffic rules.
ITS Roadwork is a company that deals with manufacturing and installation of traffic
lights so as to minimize the risk of accidents. Keeping in view the requirements,
traffic simulation is to be done. Write a program in Python that simulates a traffic
light. The program should perform the following:
(a) 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.
Function light() is called and the following is displayed depending upon return value
from light():
(i) "STOP, Life is more important than speed" if the value returned by light() is
0.
(ii) "PLEASE GO SLOW." if the value returned by light() is 1.
(iii) "You may go now." if the value returned by light() is 2.
(b) Auser-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.
(c) Display "BETTER LATE THAN NEVER" after the function trafficLight() is executed.

48
Summary

➢ A module is a separately saved unit whose functionality can be reused at will.


➢ A function is a named block of statements that can be invoked by its name.
➢ Python can have three types of functions:
• Built-in functions,
• Functions in modules, and
• User-defined functions.
➢ A Python module can contain objects like docstrings, variables, constants, classes,
objects, statements, functions
➢ A Python module has the py extension.
➢ A Python module can be imported in a program using import statement.
➢ There are two forms of Importing Python module statements:
(i) import <modulename>
(ii) from <module> import <object>
➢ The built-in functions of Python are always available; one need not import any
module for them.
➢ The math module of Python provides math functionality.
➢ Functions make program handling easier as only a small part of the program is
dealt with at a time, thereby avoiding ambiguity.
➢ The values being passed through a function-call statement are called arguments
(or actual parameters or actual arguments).
➢ The values received in the function definition/header are called parameters (or
formal parameters or formal arguments).
➢ 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 empty 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.
➢ In Python, broadly, scopes can either be global scope or local scope.
➢ A local variable having the same name as that of a global variable hides the global
variable in its function.
➢ A file that contains a collection of related functions grouped together and other
definitions is called module.
➢ A search path is the list of directories that the interpreter searches before
importing a module.
➢ A library is just a module that contains some useful definitions.
➢ The random() function generates a floating point random value from 0 to <1.
➢ A function is said to be recursive if it calls itself.
➢ There are two cases in each recursive function-the recursive case and the base
case. An infinite recursion is when a recursive function calls itself endlessly.
➢ if there is no base case or if the base case is never executed, infinite recursion
occurs.
➢ Iteration uses the same memory space for each pass contrary to recursion where
fresh memory is allocated for each successive call.
➢ Recursive functions are relatively slower than their iterative counterparts. Some
commonly used recursive algorithms are factorial, gcd, fibonacci series printing,
binary search, etc.
➢ String can be passed to a function as argument but it is used as pass by value.
➢ Tuple value cannot be modified in a function.
➢ In Python, everything is an object, so the dictionary can be passed as an
argument to a function like other variables are passed.

49

You might also like