Unit Iv

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

RGM College of Engineering & Technology (Autonomous), Nandyal

UNIT-IV
FUNCTIONS

 A program is written to solve a simple/complex problem.

 If the problem is simple, the steps involved are less, the number of lines code written are few for
solving problem and is very easy to understand and also to identify mistakes, if any, in them.

 On the other hand, if the problem is complex, the steps involved are huge and have thousands of
lines of code and become difficult to understand. Sometimes we need to write a particular block
of code that needs to be executed more than once in our program to specify one or more actions
to be performed for the large program. An error in one such block may introduce many errors in
the program. If a group of statements/block of code is repeatedly required then it is not
recommended to write these statements every time separately. We have to define these
statements as a single unit and we can call that unit any number of times based on our
requirement without rewriting. This unit is nothing but function.

The main reasons for using functions are:

 To improve the readability of code.


 Improves the re-usability of the code, same function can be used in any program rather than
writing the same code.
 debugging of the code would be easier if you use functions (errors are easy to be traced).
 reduces the size of the code, duplicate set of statements are replaced by function calls.

TYPES OF FUNCTIONS:

Python supports the 2 types of functions

1. Built-in functions
Built- in functions are pre- defined functions which comes along with python software
automatically.
Eg: id(), type(), print(), input(), eval() etc.
2. User defined functions
The functions which are developed by programmer explicitly according to business requirements,
are called user defined functions.

Syntax to create user defined functions:

def function_name(parameters):
"""doc string"""
----
-----
return value

Department of Mechanical Engineering


1
RGM College of Engineering & Technology (Autonomous), Nandyal

Note: While creating functions we can use 2 keywords


1. def (mandatory)
2. return (optional)
 create/define the function without parameters

Ex:
def wish():
print('Hello Good Morning')
wish()
wish()
wish()

output:
Hello Good Morning
Hello Good Morning
Hello Good Morning

 create/define the function with parameters

Parameters are inputs to the function. If a function contains parameters, then at the time of calling,
compulsory we should provide values otherwise, we will get error.

Ex: Write a function to take name of the student as input and print wish message b name.

def wish(name):
print('Hello Good Morning', name)
wish('sai')
wish('ravi')
wish('giri')

Output:
Hello Good Morning sai
Hello Good Morning ravi
Hello Good Morning giri

 Return statement

 The return statement is used if you want to return some values from a function.
 Return statement is used to quit the function it is executing and to pass the control back to the
statement from where it was called.

Syntax: return [expression_list / value]

Features of the return statement:

• The return statement can have an expression which gets evaluated and the value is returned or a
value directly can be returned.
• If there is no expression in the statement then the function will return None.
• If the function does not have a return statement, then the function will return None.

Department of Mechanical Engineering


2
RGM College of Engineering & Technology (Autonomous), Nandyal

• Multiple values can be returned by a Python function

Finding the addition of two numbers


Ex1:
def add(a,b):
c = a + b
return c
print('sum: ', add(2,4))

output:
sum: 6

Ex2:
def add(a,b):
c = a + b
return
print('sum: ', add(2,4))

output:
sum: None

Ex3:
def add(a,b):
c = a + b
print('sum: ', add(2,4))

output:
sum: None
Q. Write a function to check whether the given number is even or odd?
(Given in R20 24th Feb 2022)

def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)
Output
10 is Even Number
15 is Odd Number

Q. Write a function to find factorial of given number. (Given in R19, 10th August 2021)

def fact(num):
result = 1
while num >= 1:

Department of Mechanical Engineering


3
RGM College of Engineering & Technology (Autonomous), Nandyal

result =result * num


num = num - 1
return result
for i in range(1, 5):
print('The factorial of', i, 'is:', fact(i))

Output:
The factorial of 1 is: 1
The factorial of 2 is: 2
The factorial of 3 is: 6
The factorial of 4 is: 24
Ex:
Python Program to Find HCF or GCD
# Python program to find H.C.F of two numbers

# define a function
def compute_hcf(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = 54
num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))


Output:
The H.C.F. is 6

Ex: Python Program to Make a Simple Calculator


# Program make a simple calculator

# This function adds two numbers


def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):

Department of Mechanical Engineering


4
RGM College of Engineering & Technology (Autonomous), Nandyal

return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no

Department of Mechanical Engineering


5
RGM College of Engineering & Technology (Autonomous), Nandyal

Returning multiple values from a function


In other languages like C, C++ and Java, function can return almost one value. But in Python, a
function can return any number of values.
Ex4:
def calc(a,b):
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum, sub, mul, div
t = calc(20, 10)
print('The results are:')
for x in t:
print(x)

Output:
The results are:
30
10
200
2.0

Q. TYPES OF ARGUMENTS / PARAMETERS IN A FUNCTION (Given in R19, 6th January


2022)

 Parameters are used to give inputs to a function. They are specified with a pair of parentheses in
the function’s definition.

def sum(a,b): # Here a,b are the parameters


print(a+b)
sum(1,2)

 When a programmer calls a function, the values are also passed to the function.

Arguments: (Given in R19, 6 th January 2022)


An argument is a value that is passed to a function when it is called. It might be a variable, value or
object passed to a function or method as input. They are written when we are calling the function.

Example:
def sum(a,b):
print(a+b)
sum(1,2) # Here the values 1,2 are arguments

In a function, there are two types of arguments, namely formal arguments and actual arguments.
For example:

Department of Mechanical Engineering


6
RGM College of Engineering & Technology (Autonomous), Nandyal

In the above example, a and b behave as formal arguments whereas 1 and 2 behave as actual
arguments.
There are different types of arguments in Python.

1. Positional arguments:
Positional arguments are passed to the function at a proper positional order. The position and the
number of the arguments should be compared. By changing the order, the result may change
whereas by changing the number of arguments, an error message will be displayed.

Ex 1:

def add(x, y, z):


s = x - y + z
return s

res = add(3, 4, 5) # positional arguments


print(res)

Output:
4

Ex 2:

def add(x, y, z):


s = x - y + z
return s

res = add(4, 5, 3) # positional arguments


print(res)

Output:
2

Ex 3:

def add(x, y, z):


s = x - y + z
return s

res = add(3, 4) # positional arguments


print(res)

Output:

TypeError: add() missing 1 required positional argument: 'z'

2. Keyword arguments or named arguments (Given in R20, 24th February 2022)

Department of Mechanical Engineering


7
RGM College of Engineering & Technology (Autonomous), Nandyal

 Keyword arguments (or named arguments) are values that, when passed into a function, are
identifiable by specific parameter names. i.e. If the programmer knows the parameter name
used within the function then the parameter name can explicitly be used while calling the
function.
 A keyword argument is preceded by a parameter and the assignment operator, =.
 Here, the order of arguments is not mandatory, but the number of arguments should match.

Ex 1:

def add(x, y, z):


s = x + y + z
return s

res = add(3, z=4, y=5) # z and y are keyword arguments


print(res)

Output:
12
Note: The keyword and the positional arguments can be used together, but the order should be
positional and then keyword argument.
Ex 2:
def add(x, y, z): # formal parameters
s = x + y + z
return s

add(2, z=5, 10) # is not possible because a positional argument


should not come after keyword argument

Output:
File "<python-input-12-5a481a665e75>", line 1
add(2, z=5, 10) # is not possible
^
SyntaxError: positional argument follows keyword argument

Ex 3:
def add(x, y, z): # formal parameters
s = x + y + z
return s
add(2, 5, y=10) # Is this valid?

Output:
-----------------------------------------------------------------
----------
TypeError Traceback (most recent
call last)
<ipython-input-13-3aafe06a3aa0> in <module>
----> 1 add(2, 5, y=10)

Department of Mechanical Engineering


8
RGM College of Engineering & Technology (Autonomous), Nandyal

TypeError: add() got multiple values for argument 'y'

3. Default arguments:
Default arguments, are keyword arguments whose values are assigned at the time of function
definition/declaration.
Thus, at the time of calling the function, if the programmer doesn’t provide a value for the
parameter for which we specified the default argument, the function simply assumes the default
value as the argument in that case. Thus, calling the function will not result in any error even if
we don’t provide any value as an argument for the parameter with a default argument.
Ex1:

def add(x, y, z=5): # default arguments


s = x + y + z
return s
print(add(3, 4)) # here z takes default value 5
print(add(4, 3, 10)) # z's default value 5 is replaced by the
actual argument, 10

output:
12
17
Ex 2:

def add(x, y=0, z=0): # default arguments


s = x + y + z
return s
print(add(4)) # y, z takes default value 0
print(add(4, 5)) # y's default value replaced by the actual
argument value 5 and z takes default value 0
print(add(4, z=5)) # y takes default value 0 and z's default
value replaced by the actual argument, 5

Output:
4
9
9

Ex 3:
\*** non-default arguments must not follow default arguments
def add(x=0, y, z=0):
r = x + y + z
return r
print(add(4, 5))
File "<ipython-input-16-66d675e7f8c4>", line 1
def add(x=0, y, z=0):
^

Department of Mechanical Engineering


9
RGM College of Engineering & Technology (Autonomous), Nandyal

SyntaxError: non-default argument follows default argument

4. Variable Length Arguments

 A variable length argument is an argument that can accept variable number of values.
 You may need to process a function for more arguments than you specified while defining the
function i.e, where the exact number of arguments are not known in the beginning. These
arguments are called variable-length arguments.

 Points about variable length arguments in Python-


 To indicate that, the function can take variable number of arguments, you write a variable
argument using a ‘*’, for example *args. It is not mandatory to name variable length argument
as ‘*args’. What is required is *, variable name can be any variable name for example
*numbers, *names etc.

 Using variable length argument, you can pass zero or more arguments to a function.
 Values pass to *args are stored in a tuple.
 Before variable args you can have a formal argument but not after a variable args. After
variable argument you can have keyword arguments.

Ex1:

def add(*args):
print(type(args))
s = 0
for x in args:
s = s + x
return s
res = add(2, 3, 4.0, 5, 6, 7.5, 8, 9)

print(res)

Ex2:

def add(*args):
print(type(args))
s = 0
for x in args:
s = s + x
return s
add()

output:
<class 'tuple'>

5. Variable Keyword Arguments

Department of Mechanical Engineering


10
RGM College of Engineering & Technology (Autonomous), Nandyal

 Python keyword variable length argument is an argument that accept variable number of
keyword arguments (arguments in the form of key, value pair). To indicate that the function
can take keyword variable length argument you write an argument using double asterisk ‘**’,
for example **kwargs.
 Values passed as keyword variable length argument are stored in a dictionary that is
referenced by the keyword arg name.

Ex:

def add(**kwargs):
print (type(kwargs))
print (kwargs)
for var, val in kwargs.items():
print (var,'->', val)
add(a=20, b=30, c=40)

output:
<class 'dict'>
{'a': 20, 'b': 30, 'c': 40}
a -> 20
b -> 30
c -> 40

Parameter unpacking:

Ex1:

d = {'x':20, 'y':30, 'z':40}


def fun(x, y, z):
print(x + y + z)

fun(d['x'], d['y'], d['z'])


Output:
90

Ex2:

t = 2, 3, 4
def fun(x, y, z):
print(x + y + z)
fun(t[0], t[1], t[2]) # Passing parameters by unpacking them
fun(*t) # passing all parameters at once

output:
9
9

Department of Mechanical Engineering


11
RGM College of Engineering & Technology (Autonomous), Nandyal

Function vs Module vs Library:


1. A group of lines with some name is called a function
2. A group of functions saved to a file, is called Module
3. A group of Modules is nothing but Library

Distinguish between module and package:


Module is a simple python file that contains collections of functions and global variables and with
havaing .py extension file. It is an executable file.
Package: is a simple directory having collections of modules. This contains python modules, and also
having __ init__ .py file which the interpreter interprets it as a package. the package is a simply name
space. The package is also containing the sub-packages inside it.

Scope of the variables:


(Distinguish between local and global variables with suitable examples.
(Given in R19 28th August 2021)
Python supports 2 types of variables.
1. Global Variables
2. Local Variables

1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Ex:
x=15 # global variable
def f1():
print(x)
def f2():
print(x)
f1()
f2()

output:

Department of Mechanical Engineering


12
RGM College of Engineering & Technology (Autonomous), Nandyal

15
15

2. Local Variables:
 The variables which are declared inside a function are called local variables.
 Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.
Ex:
def f1():
x=15 # local variable
print(x)
def f2():
print(x) # can't access x
f1()
f2()

output:
15
NameError: name 'x' is not defined

Global keyword:
The global keyword is used:

1. To define the global variable inside the function


2. To declare the global variable available to function for modifications, if needed.

Ex1:

x=20 # global variable


def f1():
x=15 # local variable
print(x)
def f2():
print(x) # can't access local variable x
f1() # priority given to local variable
f2() # where x is not declared, the global variable gets priority.

Output:
15
20

Ex2:
def f1():
global x
x=15
print(x)
def f2():
print(x)
f1()
f2()

Department of Mechanical Engineering


13
RGM College of Engineering & Technology (Autonomous), Nandyal

output
15
15

Note: If global variable and local variable having the same name then we can access

global variable inside a function as follows

x=20 # global variable


def f1():
x=15
print(x)
print(globals()['x'])
f1()

Output:
15
20

Recursive Function
Python also supports the recursive feature, which means that a function is repeatedly calling itself.
Thus, a function is said to be recursive if the statement declared in the body of the function calls itself,
like calculating the factorial is an example of recursive function.
Ex:
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
fac(n) = n* fac(n- 1)

The main advantages of recursive functions are:


1. We can reduce length of the code and improves readability
2. We can solve complex problems very easily.

Program: Write a program using recursion that calculates the factorial of a number
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
print("Factorial of 4 is :",factorial(4))
print("Factorial of 5 is :",factorial(5))

Department of Mechanical Engineering


14
RGM College of Engineering & Technology (Autonomous), Nandyal

Output:
Factorial of 4 is : 24
Factorial of 5 is : 120

Anonymous functions: (Given in R19 6th January 2022)

Sometimes we can declare a function without any name, such type of nameless functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use (i.e for one-time usage)
Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n
lambda Function:
We can define by using lambda keyword
lambda n:n*n
Syntax of lambda Function:
lambda argument_list : expression
Note: By using Lambda Functions we can write very concise code so that readability of
the program will be improved.

Q. Write a program to create a lambda function to find square of given number?


s=lambda n:n*n
print("The Square of 4 is :",s(4))
print("The Square of 5 is :",s(5))

Output
The Square of 4 is : 16
The Square of 5 is : 25

Q. Lambda function to find sum of 2 given numbers


(Given in R19 10th August 2021)

s=lambda a, b : a + b
print("The Sum of 10,20 is:",s(10,20))
print("The Sum of 100,200 is:",s(100,200))

Output
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Q. Lambda Function to find biggest of given values.

s=lambda a, b : a if a > b else b


print("The Biggest of 10,20 is:",s(10,20))
print("The Biggest of 100,200 is:",s(100,200))

Department of Mechanical Engineering


15
RGM College of Engineering & Technology (Autonomous), Nandyal

Output:
The Biggest of 10,20 is: 20
The Biggest of 100,200 is: 200

Note:
 Lambda Function internally returns expression value and we are not required to write return
statement explicitly.
 Sometimes we can pass function as an argument to another function. In such cases lambda
functions are best choice.
 We can use lambda functions very commonly with filter (), map () and reduce () functions, b'z
these functions expect function as an argument.

filter () function:

We can use filter () function to filter values from the given sequence based on some
condition.
filter (function, sequence)
 Where function argument is responsible to perform conditional check
 Sequence can be list or tuple or string.

Q. Program to filter only even numbers from the list by using filter () function?

without lambda Function:

def isEven(x):
if x % 2==0:
return True
else:
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1)

Output:
[0,10,20,30]

with lambda Function:

l = [0,5,10,15,20,25,30]
l1 = list(filter(lambda x:x%2==0,l))
print(l1)
l2 = list(filter(lambda x:x%2!=0,l))
print(l2)

Output:
[0,10,20,30]

Department of Mechanical Engineering


16
RGM College of Engineering & Technology (Autonomous), Nandyal

[5,15,25]

map () function:

For every element present in the given sequence, apply some functionality and generate
new element with the required modification. For this requirement we should go for map () function.
Eg: For every element present in the list perform double and generate new list of doubles.
Syntax:
map (function, sequence)
The function can be applied on each element of sequence and generates new sequence.
Eg: Without lambda
l=[1,2,3,4,5]
def doubleIt(x):
return 2*x
l1=list(map(doubleIt,l))
print(l1)

Output:
[2, 4, 6, 8, 10]

with lambda

l=[1,2,3,4,5]
l1=list(map(lambda x:2*x,l))
print(l1)
output:
[2, 4, 6, 8, 10]

Eg 2: To find square of given numbers

l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1)

Output:
[1, 4, 9, 16, 25]

We can apply map() function on multiple lists also. But make sure all list should have same
length.

Syntax: map(lambda x, y : x * y, l1, l2))

x is from l1 and y is from l2

Eg3:

Department of Mechanical Engineering


17
RGM College of Engineering & Technology (Autonomous), Nandyal

l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3)
Output:
[2, 6, 12, 20]

reduce () function:

reduce () function reduces sequence of elements into a single element by applying the
specified function.
reduce(function,sequence)
reduce() function present in functools module and hence we should write import statement.
(Given in R19 28th august 2021)
Eg1:

from functools import *


l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result)

output:
150

Eg2:

l=[10,20,30,40,50]
result=reduce(lambda x,y:x*y,l)
print(result)

output:
12000000

Eg3:

from functools import *


result=reduce(lambda x, y : x + y, range(1,101))
print(result)
output:
5050
Note:
 In Python everything is treated as object.
 Even functions also internally treated as objects only.

Department of Mechanical Engineering


18
RGM College of Engineering & Technology (Autonomous), Nandyal

Eg:
def f1():
print("Hello")
print(f1)
print(id(f1))

Output
<function f1 at 0x000002AE9F90A290>
2949024621200

Fruitful Functions

These are the functions that return a value after their completion. A fruitful function must always
return a value to where it is called from. A fruitful function can return any type of value may it be
string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one
variable, the value to be returned can be an array or a vector. A fruitful function can also return
multiple values.

Ex1: Ex2:

def fun2(a,b): import math


return a+b def area(radius):
print(fun2(5,8)) a = math.pi*radius**2
return a
print(area(2))

Higher Order Functions (Given in R20, 24 th February 2022)


Because functions are objects we can pass them as arguments to other functions. Functions that can
accept other functions as arguments are also called higher-order functions. In the example below,
a function greet is created which takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Good Morning")
print(greeting)
greet(shout)
greet(whisper)

Output
GOOD MORNING

Department of Mechanical Engineering


19
RGM College of Engineering & Technology (Autonomous), Nandyal

good morning

Modules
A module in python is a set of re-usable classes, functions, and variables. If we need those classes,
functions or variables in our project, we just import them.
Modules can be either:
 Built in modules

Built-in modules come with default Python installation. Some commonly used Python built-in
modules are datetime, os, math, sys, random, etc.

 User-defined modules
The modules which the user defines or create are called a user-defined module. We can create our
own module, which contains classes, functions, variables, etc., as per our requirements.

Create a Module
To create a module, create a Python file with a .py extension.
Ex:

x = 10
y = 20
def add(a,b):
print('The Sum : ',a+b)
def product(a,b):
print('The product :', a*b)

 save the above code as example.py, itself is a module.


 example.py, module contains two variables and 2 functions.

CALL A MODULE

If we want to use members of module in our program then we should import that module.
Syntax of importing a module

import modulename

We can access members by using module name.

modulename.variable
modulename.function()

Ex:

import example

Department of Mechanical Engineering


20
RGM College of Engineering & Technology (Autonomous), Nandyal

print(example.x)
example.add(10,20)
example.product(10,20)

Output:
10
The Sum : 30
The product : 200
Note: Whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently. This is available at __pycache__ file, which is
available at current working directory.
Advantages of Modules
The main purpose of creating modules is to make Python code reusable.
 Code Re-usability has the following benefits:

– Saves developer’s time


– Allows sharing of classes, functions, etc...
– Enriches the whole developing process
 Readability improved
 Maintainability improved

Module aliasing (Renaming a module at the time of import) [R19, 28th August2021]
We can create alias name for a module. This can be done as follows:
import example as ex
Here, example is original module name and ex is alias name. We can access members by using alias
name ex.
Ex:
import example as ex
print(ex.x)
ex.add(10,20)
ex.product(10,20)

Output:
10
The Sum : 30
The product : 200

Ex:
import example as ex
print(example.x)
example.add(10,20)
example.product(10,20)
output:

Department of Mechanical Engineering


21
RGM College of Engineering & Technology (Autonomous), Nandyal

Traceback (most recent call last):


NameError: name 'example' is not defined
Note:
Once we define alias name for a module, compulsory you should use alias name only. original names
by default will be gone related to that particular file.
from ... import
We can import particular members of module by using from ... import.
The main advantage of this is we can access members directly without using module name.
Ex:

from example import x, add


print(x)
add(10,20) # Executed in Editplus editor
product(10,20)

Output:
Traceback (most recent call last):
NameError: name 'product' is not defined
We can import all members of a module as follows
Eg

from example import*


print(x)
add(10,20) # Executed in Editplus editor
product(10,20)

Output:
10
The Sum : 30
The product : 200

member aliasing

Similar to module aliasing, member aliasing also possible in python. This can be done as follows:
from example import x as y,add as sum
print(y)
sum(10,20)
Note: Once we defined as alias name, we should use alias name only and we should not use original
name.

Department of Mechanical Engineering


22
RGM College of Engineering & Technology (Autonomous), Nandyal

Finding members of module by using 'dir()' function

(Given in 28th august 2021& 8th april 2021)


Python provides inbuilt function dir() to list out all members of current module or a specified module.
dir() ===>To list out all members of current module
dir(moduleName)==>To list out all members of specified module
Eg 1: To display members of current module

x=10
y=20
def f1():
print("Hello")
print(dir())

Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'add', 'ex',
'example', 'f1', 'product', 'sum', 'x', 'x1', 'y']
Eg2: To display members of particular module
Consider example.py module,
import example module in another module, called as run.py,
import example
print(dir(example))
the above two lines of code will be saved as run.py and run we will get
output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'add', 'product', 'x', 'y']
Note:
For every module at the time of execution Python interpreter will add some special properties
automatically for internal use.
Eg: '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__'

The Special variable '_ name _'

 For every Python program , a special variable _ name_ will be added internally. This variable stores
information regarding whether the program is executed as an individual program or as a module.
 If the program executed as an individual program then the value of this variable is _ main_.
 If the program executed as a module from some other program then the value of this variable is the
name of module where it is defined.
 Hence by using this _ name_ variable we can identify whether the program executed directly or as a
module.

Department of Mechanical Engineering


23
RGM College of Engineering & Technology (Autonomous), Nandyal

Working with math module

Python provides inbuilt module math.


This module defines several functions which can be used for mathematical operations.
The math module have various functions:
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
5. log(x)
6. sin(x)
7. tan(x) and many more

Random Module
The random module is used to generate various random numbers. It comprises several functions that
are defined below:
1. random() Function: It produces any float value in the range 0 to 1, without inclusive 0 and 1.

2. randint() Function: It produces any random integer between specified numbers, with including
them.

Example:

Department of Mechanical Engineering


24
RGM College of Engineering & Technology (Autonomous), Nandyal

3. uniform() Function: It produces any random float values between specified numbers, without
including them.

Example:

4. randrange ([begin], end, [step]): It produces a random number from the defined range. Here, the
begin argument is optional and if not defined, then the by- default value is 0. The step argument is
also optional and if not defined then, the by- default value is 1.

Ex:

Ex:

Ex:

5. choice() Function: It gives a random object from the specified list or the tuple.

Example:

Department of Mechanical Engineering


25
RGM College of Engineering & Technology (Autonomous), Nandyal

Q 1. Write a Python program to generate a six digit random number as One Time Password
(OTP).

for i in range(10):
for x in range(6):
print(randint(0,9),end='') # Correct version
print()

Q 2. Write aPython program to generate a random password of 6 length.


Within the OTP --
1,3,5 positions are alphabets.

2,4,6 positions are digits.

from random import *

for i in range(6):

print(chr(randint(65,90)),randint(0,9),chr(randint(65,90)),randint(0,9),chr(randint(65,90)), randint(0,9), sep ='')

Department of Mechanical Engineering


26
RGM College of Engineering & Technology (Autonomous), Nandyal

File I/O
File is a collection of data stored externally on an external media (not in RAM, RAM is a volatile
memory). i.e. on permanent storage devices (eg. Hard disk, is a non-volatile memory) with a
name.
Content of file can be simple text, binary data (image, audio, video) etc...

Why files?
Till now, we were taking the input from the console and writing it back to the console to interact
with the user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and only a limited amount of data can be displayed on the console since the
memory is volatile, it is impossible to recover the programmatically generated data again and
again.
File handling plays an important role when the data needs to be stored permanently in the file.

Types of Files

Python supports two types of files


1.
2. Text files:
A text file consists of human-readable characters, which can be opened by any text editor.
Common extensions for text file formats:
Web standards: html, xml, css, svg, json,...
Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh,...
Documents: txt, tex, markdown, asciidoc, rtf, ps,...
Configuration: ini, cfg, rc, reg,...
Tabular data: csv, tsv,...
3.
4. Binary files
binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.

Common extensions for binary file formats:


Images: jpg, png, gif, bmp, tiff, psd,...
Videos: mp4, mkv, avi, mov, mpg, vob,...
Audio: mp3, aac, wav, flac, ogg, mka, wma,...
Documents: pdf, doc, xls, ppt, docx, odt,...
Archive: zip, rar, 7z, tar, iso,...
Database: mdb, accde, frm, sqlite,...
Executable: exe, dll, so, class,
Every file has two attributes:
File Name is the name of the file
File Path is the location of the file
File name consists of two parts normally separated by a '.' (dot) e.g. sample1.txt

Department of Mechanical Engineering


27
RGM College of Engineering & Technology (Autonomous), Nandyal

Name is the name of the file (sample1 in sample1.txt)


Extension is the type of the file (txt in sample1.txt) which means it is a text file containing
printable characters.
The extension also specifies the default program used to open the file. For example .txt file is
opened with Notepad, .c files are opened with c compiler, .exe files are executed by the OS etc.)
There is no restriction on the number of characters in the extension, but if there is no associated
program with that extension, the file cannot be opened or read.
There is no check that the extension specified is correct.

Opening a File:
Before performing any operation (like read or write) on the file, first we have to create a file
object that is associated with a physical file is called opening a file. To open that file we should
use Python's inbuilt function open ( ).
But at the time of open, we have to specify mode, which represents the purpose of opening file.
fileVariable = open(filename, mode)
The open function returns a file object for filename. The mode parameter is a string that specifies
how the file will be used (for reading or writing), as shown below.
The allowed modes in Python are
It is the default mode. The file gets opened for reading purpose only and the cursor
r points at the starting of the file.
If the specified file does not exist then we will get FileNotFoundError

The file gets opened for writing. If the file exists of the mentioned name, it gets
w
overwritten else another file will be created.

The existing file is opened for the appending purpose. If the file exists, the pointer
a points at the end of file as the file is in the append mode otherwise, a new file will be
created for the writing purpose.

The file gets open for reading and writing as well. The existing data is the file doesn’t
r+
gets deleted. The cursor is kept at the starting of file.

File gets open for both reading and writing as well. It will overwrite the file if the file
w+
exists. Otherwise, another file will be deployed.

The file gets open for append and read purpose. If the file exists, the pointer is at the
a+ end of file. The file opens in append mode whereas if the file doesn’t exist, a new file
will be created for read and write purpose.

The file gets open for exclusive creation for writing the data. The operation fails if
x
the file already exists.

Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then
these represent binary files.

Department of Mechanical Engineering


28
RGM College of Engineering & Technology (Autonomous), Nandyal

Eg: rb,wb,ab,r+b,w+b,a+b,xb
For example, the following statement opens a file named Scores.txt in the current directory for
reading:
input = open("Scores.txt", "r")
You can also use the absolute filename to open the file in Windows, as follows:
input = open(r"c:\pybook\Scores.txt", "r")
The statement opens the file Scores.txt that is in the c:\pybook directory for reading. The r prefix
before the absolute filename specifies that the string is a raw string, which causes the Python
interpreter to treat backslash characters as literal backslashes. Without the r prefix, you would
have to write the statement using an escape sequence as:
input = open("c:\\pybook\\Scores.txt", "r")
illustrate opening files with a neat diagram. (given in R19 10th august 2021)

Closing a File:
Opening files consume system resources, and, depending on the file mode, other programs may
not be able to access them. It is important to close the file once the processing is completed. After
the file handler object is closed, you cannot further read or write from the file. Any attempt to use
the file handler object after being closed will result in an error.
The syntax for close() function is,
file_handler.close()
Attributes/properties of a file object:
Attribute Information Obtained

Name File name will be returned.

Mode The access mode with which the file has opened will be returned.

Closed If the file is closed, it will return True. Else False will be returned.

readable() It will return the Boolean value mentioning whether the file is readable or not.

writable() It will return the Boolean value mentioning whether the file is writable or not

Department of Mechanical Engineering


29
RGM College of Engineering & Technology (Autonomous), Nandyal

Writing data to text files:

For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will be positioned at the
beginning of the file. On the other hand, in append mode, new data will be added at the end of the
previous data as the file object is at the end of the file.
After opening the file, we can use the following methods to write data (character data) in the file.
 write() - for writing a single string
 writelines() - for writing a sequence of strings/list of lines

write():

write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on single execution of the write() method.
Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
Ex:
def main():
outfile = open("Presidents.txt", "w")# Open file for output
outfile.write("George Bush\n")
outfile.write("Barack Obama\n")
outfile.write("Bill Clinton\n")
outfile.close() # Close the output file
main() # Call the main function
The program opens a file named Presidents.txt using the w mode for writing data.
If the file does not exist, the open function creates a new file. If the file already exists, the contents
of the file will be overwritten with new data. You can now write data to the file.
When a file is opened for writing or reading, a special marker called a file pointer is positioned
internally in the file. A read or write operation takes place at the pointer’s location.
When a file is opened, the file pointer is set at the beginning of the file. When you read or write
data to the file, the file pointer moves forward.
The program invokes the write method on the file object to write three strings.

Department of Mechanical Engineering


30
RGM College of Engineering & Technology (Autonomous), Nandyal

The program closes the file to ensure that data is written to the file. After this program is
executed, three names are written to the file. You can view the file in a text editor, as shown in
Figure.

Instead of overriding if we want append operation then we should open the file as follows.
def main():
outfile = open("Presidents.txt", "a")# Open file for output
outfile.write("George Bush\n")
outfile.write("Barack Obama\n")
outfile.write("Bill Clinton\n")
outfile.close() # Close the output file
main() # Call the main function

On execution, write () returns the number of characters written on to the file.


The write() actually writes data onto a buffer. When the close() method is executed, the contents
from this buffer are moved to the file located on the permanent storage.

Writelines() method:

This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method. Unlike write(), the writelines() method
does not return the number of characters written in the file. The following code explains the use of
writelines().
Code:
f=open("abcd.txt",'w')
list=["sunny\n","bunny\n","vinny\n","chinny"]
f.writelines(list)
print("List of lines written to the file successfully")

Department of Mechanical Engineering


31
RGM College of Engineering & Technology (Autonomous), Nandyal

f.close()

Reading Character Data from text files:


We can read character data from text file by using the following read methods.
read()-> To read total data from the file
read(n) -> To read 'n' characters from the file
readline()->To read only one line
readlines()-> To read all lines into a list
Eg 1: To read total data from the file
f=open("abc.txt",'r')
data=f.read()
print(data)
f.close()
Output
sunny
bunny
chinny
vinny
Eg 2: To read only first 10 characters:
f=open("abc.txt",'r')
data=f.read(10)
print(data)
f.close()
Output
sunny
bunn
Eg 3: To read data line by line:
f=open("abc.txt",'r')
line1=f.readline()
print(line1,end='')
line2=f.readline()
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
Output
sunny
bunny

Department of Mechanical Engineering


32
RGM College of Engineering & Technology (Autonomous), Nandyal

chinny
Eg 4: To read all lines into list:
f=open("abc.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
Output
sunny
bunny
chinny
vinny

Eg 5:
f=open("abc.txt","r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
Output
sun
ny
bunn
Remaining data
y
chinny
vinny

Ex:
myobject=open("myfile.txt", 'w')
list = ['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
myobject.writelines(list)
myobject.close()
In case we want to display each word of a line separately as an element of a list, then we can use
split() function. The following code demonstrates the use of split() function.
myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.split()
print(words)
output:
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements of a list. However, if splitlines() is used instead

Department of Mechanical Engineering


33
RGM College of Engineering & Technology (Autonomous), Nandyal

of split(), then each line is returned as element of a list, as shown in the output below
myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.splitlines()
print(words)
Output:
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string from the user and writes it to a text file.
Thereafter, the same program reads the text file and displays it on the screen.
Program: Writing and reading to a text file
fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")

fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject:
print(str)
fobject.close()

In Program, the file named testfile.txt is opened in write mode and the file handle named fobject is
returned. The string is accepted from the user and written in the file using write(). Then the file is
closed and again opened in read mode. Data is read from the file and displayed till the end of file
is reached.

The with statement:


The with statement can be used while opening a file. We can use this to group file
operation statements within a block.
The advantage of with statement is it will take care closing of file, after completing all
operations automatically even in the case of exceptions also, and we are not required to close
explicitly.
Eg:
with open("abc.txt","w") as f:
f.write("department\n")
f.write("mechanical\n")
f.write("engineering\n")
print("Is File Closed: ",f.closed)
print("Is File Closed: ",f.closed)

Output

Department of Mechanical Engineering


34
RGM College of Engineering & Technology (Autonomous), Nandyal

Is File Closed: False


Is File Closed: True

SETTING OFFSETS IN A F ILE

The functions that we have learnt till now are used to access the data sequentially from a file. But
if we want to access data in a random fashion, then Python gives us seek() and tell() functions to
do so.
The tell() method
==>We can use tell() method to return current position of the cursor(file pointer) from beginning
of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
Syntax: file_object.tell()
abc.txt file contains
department
mechanical
engineering

f=open("abc.txt","r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
Output:
0
de
2
par
5

seek():
We can use seek() method to move cursor(file pointer) to specified location.
[Can you please seek the cursor to a particular location]
f.seek(offset, fromwhere)
offset represents the number of positions
The allowed values for second attribute(from where) are
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file
Note: Python 2 supports all 3 values but Python 3 supports only zero.

Ex:
data="All Students are VERY GOOD"
f=open("file.txt","w")
f.write(data)
with open("file.txt","r+") as f:
text=f.read()
print(text)

Department of Mechanical Engineering


35
RGM College of Engineering & Technology (Autonomous), Nandyal

print("The Current Cursor Position: ",f.tell())


f.seek(17)
print("The Current Cursor Position: ",f.tell())
f.write("GEMS!!!")
f.seek(0)
text=f.read()
print("Data After Modification:")
print(text)
Output:
All Students are VERY GOOD
The Current Cursor Position: 26
The Current Cursor Position: 17
Data After Modification:
All Students are GEMS!!!OD

How to check a particular file exists or not?


We can use os library to get information about files in our computer.
os module has path sub module, which contains isfile() function to check whether a particular file
exists or not?
os.path.isfile(fname)
Q. Write a program to check whether the given file exists or not. If it is
available then print its content?
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
print("The content of file is:")
data=f.read()
print(data)
Output:
Enter File Name: abc.txt
File exists: abc.txt
The content of file is:
department
mechanical
engineering

Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
Q. Program to print the number of lines,words and characters present in the given file?
File contains the following:
department
mechanical

Department of Mechanical Engineering


36
RGM College of Engineering & Technology (Autonomous), Nandyal

engineering

import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split()
wcount=wcount+len(words)
print("The number of Lines:",lcount)
print("The number of Words:",wcount)
print("The number of Characters:",ccount)

Output:
Enter File Name: abc.txt
File exists: abc.txt
The number of Lines: 3
The number of Words: 3
The number of Characters: 34

Traversing text file:


let us create one single program to read and write data using a single file object. Since both the
operations have to be performed using a single file object, the file will be opened in w+ mode

fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()

Department of Mechanical Engineering


37

You might also like