Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Chapter 7 Functions

Uploaded by

vineetjambagi28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 7 Functions

Uploaded by

vineetjambagi28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter 7 Functions

1 Introduction :

The programs gets complex as the line of codes increases, and also it is
difficult to manage lengthy programs. So the programs are divided into
separate independent blocks of code or separate sub-problems with
different names and specific functionalities is known as modular
programming.

2. Functions :

Definition: Functions are the subprograms that perform specific task.


Functions are the small modules.

• Through functions we can achieve nodularity and reusability.


• Once defined, a function can be called repeatedly from different
places of the program without writing all the codes of that function
everytime, or it can be called from inside another function, by
simply writing the name of the function and passing the required
parameters.

2.1 The Advantages of Function

• Increases readability, particularly for longer code as by using


functions, the program is better organized
• When programs are divided into functions it is easy to understand.
• Reduces code length as same code is not required to be written at
multiple places in a program.
• When length of the program is less and also divided into functions
debugging is easier.
• Increases reusability, as function can be called from another function
or another program. Thus, we can reuse or build upon already defined
functions and avoid repetitions of writing the same piece of code.
• Work can be easily divided among team members and completed in
parallel.

3. User defined Functions

The functions those are defined by the user are called user defined `
functions, or in other words a function defined to achieve some task as
per the programmer's requirement is called a user defined function

3.1 Creating User Defined Function

SURANA IND. PU COLLEGE Page 1 of 10


The syntax to define a function is:

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 - through which we pass values to a function. They are optional.
• 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?")

Example Program :

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

In order to execute the function addnum(), we need to call it. The function can
be called in the program by writing function name followed by ()

Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11
3.2 Arguments and Parameters

A parameter is the variable listed inside the parentheses in the function


definition.An argument is the value that is sent to the function when it is
called.

SURANA IND. PU COLLEGE Page 2 of 10


Example :

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

(A) String as Parameters

Not only numbers can be passed as parameters, we can pass


strings as parameters as well

Example :
Program :Function to display full name

def fullname(first,last): #+ operator is used to concatenate strings


fullname = first + " " + last
print("Hello",fullname)
first = input("Enter first name: ")
last = input("Enter last name: ") #function call 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 predecided and assigned to the parameter
when the function call does not have its corresponding argument.

Example Program:
Write a program that accepts numerator and denominator of a fractional
number and calls a user defined function mixedFraction() when the

SURANA IND. PU COLLEGE Page 3 of 10


fraction formed is not a proper fraction. The default value of
denominator is 1. The function displays a mixed fraction only if the
fraction formed by the parameters does not evaluate to a whole number.

def mixedFraction(num,deno = 1):


remainder = num % deno
#check if the fraction does not evaluate to a whole number
if remainder!= 0:
quotient = int(num/deno)
print("The mixed fraction=", quotient,"(",remainder, "/",
deno,")")
else:
print("The given fraction evaluates to a whole number")

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


deno = int(input("Enter the denominator: "))
print("You entered:",num,"/",deno)

if num > deno:


mixedFraction(num,deno)
else:
print("It is a proper fraction")

3.3 Functions Returning Value


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

Functions that do not return any value are called void functions.
But a situation may arise, wherein 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.

So far we have learnt that a function may or may not have


parameter(s) and a function may or may not return any value(s). In
Python, as per our requirements, we can have the function in
either of the following ways:
• 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)

SURANA IND. PU COLLEGE Page 4 of 10


3.4 Flow of Execution
• The order in which the statements in a program are executed.
• The Python interpreter starts executing the instructions one by
one, from top to bottom.
• When the interpreter encounters a function definition, the
statements inside the function are not executed until the function
is called.
• When the interpreter encounters a function call, there is a
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.

4. Scope of a Variable
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,

(A) Global Variable In Python, a variable that is defined outside any


function or any block is known as a global variable. It can be
accessed in any functions defined onwards. 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.

5. Built-in functions

Built-in functions are the ready-made functions in Python that are


frequently used in programs.

SURANA IND. PU COLLEGE Page 5 of 10


input(), int() and print() are the built-in functions. The set of instructions
to be executed for these built-in functions are already defined in the
python interpreter.

SURANA IND. PU COLLEGE Page 6 of 10


5.2 Module
• A function is a grouping of instructions, a module is a grouping of
functions.
• function is used to simplify the code and to avoid repetition. For a
complex problem, it may not be feasible to manage the code in one
single file. Then, the program is divided into different parts under
different levels, called modules
• Also, suppose we have created some functions in a program and
we want to reuse them in another program. In that case, we can
save those functions under a module and reuse them. A module is
created as a python (.py) file containing a collection of function
definitions.
• To use a module, we need to import the module. Once we import a
module, we can directly use all the functions of that module. The
syntax of import statement is as follows:

import modulename1 [,modulename2, …]

This gives us access to all the functions in the module(s). To call a


function of a module, the function name should be preceded with
the name of the module with a dot(.) as a separator. The syntax is
as shown below:
modulename.functionname()

(A) Built-in Modules Python library has many built-in modules


some commonly used are:
• math
• random
• statistics

1. Module name : math


It contains different types of mathematical functions. Most of
the functions in this module return a float value. Some of
the commonly used functions in math module are

SURANA IND. PU COLLEGE Page 7 of 10


2. Module name : random
This module contains functions that are used for generating
random numbers. Some of the commonly used functions in
random module are

SURANA IND. PU COLLEGE Page 8 of 10


3. Module name : statistics
This module provides functions for calculating statistics of
numeric (Real-valued) data. Some of the commonly used
functions in statistics module are

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")
• The modules in the standard library can be found in the Lib folder of
Python.

SURANA IND. PU COLLEGE Page 9 of 10


(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. It loads only
the specified function(s) instead of all the functions in 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. Rather we can directly call the function as
shown in the following examples:

SURANA IND. PU COLLEGE Page 10 of 10

You might also like