0% found this document useful (0 votes)
2 views34 pages

Functions in Python

The document provides an overview of Python functions and file handling, emphasizing the importance of modularity and reusability in programming. It covers user-defined functions, built-in functions, variable scope, and the use of modules, along with examples and syntax. Additionally, it discusses the Python standard library and includes assignments for further understanding of the concepts presented.
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)
2 views34 pages

Functions in Python

The document provides an overview of Python functions and file handling, emphasizing the importance of modularity and reusability in programming. It covers user-defined functions, built-in functions, variable scope, and the use of modules, along with examples and syntax. Additionally, it discusses the Python standard library and includes assignments for further understanding of the concepts presented.
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

Python Functions

and
File Handling

By- Mr. Meher J. Bharti


Agenda

Chapter- 5
Functions
Defining User Defined Functions
Built In Functions
Modules
Import and from keywords
File Handling
Pickle Module
Definition
• In programming, the use of function is one of
the means to achieve modularity and reusability.
• Function can be defined as a named group of
instructions that accomplish a specific task when
it is invoked.
• 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, if
any.
advantages of using functions
• Increases readability, particularly for longer code
as by using functions, the program is better
organised and easy to understand.
• Reduces code length as same code is not required
to be written at multiple places in a program. This
also makes debugging 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.
USER DEFINED FUNCTIONS
A function defined to achieve some task as per the
programmer's requirement is called a user defined
function.
Syntax:
def <function_name> (Arg1, Arg2, …., Argn):
Statement 1
Statement 2
…….
Statement n
return Value
• a function may or may not have parameters.
Also, a function may or may not return a value.
• Function header always ends with a colon (:).
• Function name should be unique.
• Rules for naming identifiers also applies for
function naming.
• The statements outside the function
indentation are not considered as part of the
function.
Example 1
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)
#function call
addnum()
Example 2
def sumSquares(n):
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)
More Examples
• Write a program using user defined function that
accepts an integer and increments the value by 5.
Also display the id of argument (before function
call), id of parameter before increment and after
increment.
• Write a program using a user defined function
myMean() to calculate the mean of floating
values stored in a list.
• Write a program using a user defined function
calcFact() to calculate and display the factorial of
a number num passed as an argument.
String as Parameter
Write a program using a user defined function
that accepts the first name and lastname as
arguments, concatenate them to get full name
and displays the output as:
Hello full name
For example, if first name is Gyan and lastname
is Vardhan, the output should be: Hello Gyan
Vardhan
def fullname(first,last):
fullname = first + " " + last
print("Hello",fullname)
first = input("Enter first name: ")
last = input("Enter last name: ")
fullname(first,last)

• Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan
Default 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-
def area(r,pie=3.14):
a=pie * r *r
print('Area= ',a)
area(4,3)
Flow of Execution
Flow of execution can be defined as the order in
which the statements in a program are
executed.
The Python interpreter starts executing the
instructions in a program from the first
statement.
The statements are executed one by one, in the
order of appearance from top to bottom.
Dive in Details
When the interpreter encounters a function definition,
the statements inside the function are not executed
until the function is called. Later, when the interpreter
encounters a function call, there is a little 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.
Returning many values
def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
#a tuple is returned consisting of 2 values
return (area,perimeter)
l = float(input("Enter length of the rectangle: "))
b = float(input("Enter breadth of the rectangle: "))
#value of tuples assigned in order they returned
area,perimeter = calcAreaPeri(l,b)
print("Area is:",area,"\nPerimeter is:",perimeter)
SCOPE OF A VARIABLE
• A variable defined inside a function cannot be
accessed outside it. Every variable has a well-
defined accessibility. 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 variable that has global scope is known as a
global variable .
• A variable that has a local scope is known as a
local variable.
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.
Local Variable
• A variable that is defined inside any function
or a block is known as a local variable. It can
be accessed on ly in the function or a block
where it is defined. It exists only till the
function executes.
NOTE 
• Any modification to global variable is
permanent and affects all the functions where
it is used.
• If a variable with the same name as the global
variable is defined inside a function, then it is
considered local to that function and hides the
global variable.
• If the modified value of a global variable is to
be used outside the function, then the keyword
global should be prefixed to the variable name
in the function.
Program to access any variable
outside the function
num = 5
def myfunc1():
global num
print("Accessing num =",num)
num = 10
print("num reassigned =",num)
# Note the output
myfunc1()
print("Accessing num outside myfunc1",num)
PYTHON STANDARD LIBRARY
Python has a very extensive standard library. It is
a collection of many built in functions that can
be called in the program as and when required,
thus saving programmer’s time of creating those
commonly used functions every time.
Built-in functions are the ready-made functions
in Python that are frequently used in programs.
Module
• Other than the built-in functions, the Python
standard library also consists of a number of
modules. While a function is a grouping of
instructions, a module is a grouping of functions.
• 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.
Syntax: import module1 [,module2, …]
To Use  [Link]()
import

• 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")
From
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 fname [,fname,...]
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.
"""Docstrings"""

Is also called Python documentation strings. It is


a multiline comment that is added to describe the
modules, functions, etc. They are typically added
as the first line, using 3 double quotes.
SUMMARY
• In programming, functions are used to achieve
modularity and reusability.
• Function can be defined as a named group of
instructions that are executed when the
function is invoked or called by its name.
Programmers can write their own functions
known as user defined functions.
• The Python interpreter has a number of
functions built into it. These are the functions
that are frequently used in a Python program.
Such functions are known as built-in functions.
• An argument is a value passed to the function during
function call which is received in a parameter defined
in function header.
• Python allows default value to the parameter.
• A function returns value(s) using return statement.
• Multiple values in are returned through a Tuple.
• Flow of execution can be defined as the order in
which the statements in a program are executed.
• The part of the program where a variable is accessible
is defined as the scope of the variable.
• A variable that is defined outside any particular
function or block is known as a global variable. It can
be accessed anywhere in the program.
• A variable that is defined inside any function or block
is known as a local variable. It can be accessed only
in the function or block where it is defined. It exists
only till the function executes or remains active.
• The Python standard library is an extensive collection
of functions and modules that help the programmer in
the faster development of programs.
• A module is a Python file that contains definitions of
multiple functions.
• A module can be imported in a program using import
statement.
• Irrespective of the number of times a module is
imported, it is loaded only once.
• To import specific functions in a program from a
module, from statement can be used.
Assignment 4-1
• How is built-in function pow() function different from
function [Link]() ? Explain with an example.
• Using an example show how a function in Python can
return multiple values.
• Differentiate between following with the help of an
example:
a) Argument and Parameter
b) Global and Local variable
• Out of random() and randint(), which function should
we use to generate random numbers between 1 and 5.
Justify.
• How is [Link](89.7) different from [Link] (89.7)?

You might also like