Chapter 7 Functions
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 :
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
Where:
Example:
def display(name):
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
Example :
Program :Function to display full name
Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan
Example Program:
Write a program that accepts numerator and denominator of a fractional
number and calls a user defined function mixedFraction() when the
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.
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,
5. Built-in functions
Note :
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: