Basic Python II

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

Basic Python II

 List, Tuple, Dictionary


 List
 List functions & Methods
 Tuple
 Tuple functions & Methods
 Dictionary
 Dictionary Functions & Methods
 Functions & Modules
 Creating a Function
 Types of function
 Types of function arguments
 Modules and Packages
 Mathematical functions
 random module
 statistics module
 File Handling
 Steps to create data file
 Writing content into a text file
 Reading data from text file
 Working with binary files
 Write data into a Binary File
 Reading data from a Binary File

Reference:
https://ladderpython.com/lesson/installing-python-idle/
Python List with Examples | List in Python
3
You must first complete Display output in Python 3 | print() function in Python 3
before viewing this Lesson

What is a List in Python?


List is a collection of values within pair of square brackets. These

values must be separated by commas. These values can be of any data

type.

Lists are mutable i.e. we can modify the elements of a list.

1. Creating a List
To create a list, we can put multiple values within the pair of square

brackets.

Syntax:

Listname = [value1,value2,value3,……. valueN ]

Listname refers to name of list defined by the programmer.

[ ] Pair of square brackets specifies that it is a list.

value1, value2,value3, …. valueN are different values stored in the

list.

Examples:
[ 1,2,3,] List of integers

List of numbers(integers and floating


[ 1,2.5,3,9.5 ]
point)

[‘a’,’b’,’c’ ] List of characters

[ ‘a’,1,’b’,3.5,’,‘zero’ ] List of mixed values

[‘First’,’Second’,’Third’ ] List of strings

2. Creating an empty list


Empty list contains no element in it. It is equivalent of 0 or ‘

‘(blank). So it has truth value as False.

We can create an empty list in two ways:

1. By specifying an empty pair of square


brackets
Example:
List1=[ ]

Note: List1 is an empty list containing no element in it.


2. By using list() function without anything
within the pair of parenthesis.
Example:
List2= list ( )

Note: List2 is an empty list containing no element in it.

3. Creating a Long List


If list contains many elements which are not able to fit on one line,

we can split it across several lines as given below:

List1=[0,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,

41,43,45,47,49]

Opening square bracket appears in the beginning and closing square

brackets appears at the end of list.

>>> list1=[10,20,30,40,50,60,70,80,90,100,

120,130,140,150]

>>> list1

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150]

4. Nested list
If one list is enclosed within another list, it is known as nested list.

A list can contain another list as its element. Such a list is called

nested list

Example:

List1=[1,2,[5,6,7],9]

List1 is a nested list with four elements:3,4,[5,6,7]and9 .

Here [5,6,7] is nested list.

>>> list2=[1,2,[5,6,7],9]
>>> list2
[1, 2, [5, 6, 7], 9]

5. Creating a List from Existing


Sequence
We can use list() function to create list from existing sequences as

given below:

listname=list(<sequence>)

Here, listname refers to name of list specified by the programmer.

<sequence> refers to existing sequence object like string, tuple, set or

other list
Python Creates the individual elements of the list from the individual

elements of sequence.

Example 1:

Creating a list from existing string

>>> newlist1=list(‘Lovejot’)
>>> newlist1
[‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’]

Description

List named newlist1 is created from string ‘lovejot’

It converts each individual character of string into individual list elements:

[‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’]

Example 2:

Creating a list from existing tuple

>>> t1=(1,3,5,7,9)
>>> newlist2=list(t1)
>>> newlist2
[1, 3, 5, 7, 9]

Description

List named newlist2 is created from existing tuple t1 = (1,3,5,7,9)


It converts each individual element of tuple into individual list elements:

[1,3,5,7,9]

Example 3:

Creating a list from existing set

>>> s1={2,4,6,8,10}
>>> newlist3=list(s1)
>>> newlist3
[2,4, 6,8,10]

Description

List named newlist3 is created from existing set s1 = {2,4,6,8,10}

It converts each individual element of set into individual list elements:

[2,4,6,8,10]

6. Reading a List from keyboard


We can also use list() function to read elements of a list by using keyboard.

Example:
Reading list from keyboard

>>> list3=list(input(‘Enter list =’))


Enter list = [‘I’,’n’,’d’,’i’,’a’]
>>> list3
[‘I’, ‘n’, ‘d’, ‘i’, ‘a’]

Description

List name list3 is entered from keyboard as [‘I’,’n’,’d’,’i’,’a’]

7. Accessing elements of a List


Each element of a list has an index associated with it.

Elements of a List are also indexed in two ways:

1. FORWARD INDEXING AS 0,1,2,3,…


2. BACKWARD INDEXING AS -1,-2,-3,…

Example

we have a list named list1=[10,30,40,50,60,99]

Elements of above list are indexed as follows:


Index of first element of List is 0 (Forward Indexing) and -6

(Backward Indexing)

So we an access first element of above list as list1[0] or list1[-6]

Similary we can access last element of above list as list1[5] or list1[-

1].

Example

>>> classes=[‘xii’,’xi’,’x’,’ix’]

>>> classes[0]
‘xii’ #First element of list is shown.

>>> classes[2]
‘x’ #Third element of list is shown.

>>> classes[-1]
‘ix’ #Last element of list is shown.

>>> classes[-3]
‘xi’ #Second element of list is shown.

8. Slicing of List elements


We can view specific values in a list by specifying the range of

indexes within the pair of square brackets as:

Listname[First_index,Last_index,Gap].

Listname is the name of list whose values you want to view.


First_index refers to the starting index.

Last_index refers to ending index.

Gap refers to the gap in indexes

Example

>>> list1=[10,20,30,40,50,60,70]

>>> list1[0:3]
[10, 20, 30]#List elements at indexes 0,1,2 are shown.

>>> list1[2:6]
[30, 40, 50, 60]#List elements at indexes 2,3,4,5 are shown.

>>> list1[-6:-3]
[20, 30, 40]#List elements at indexes -6,-5,-4 are shown.

>>> list1[0:7:2]
[10, 30, 50, 70]#List elements at indexes 0,2,4,6 are shown.

>>> list1[-7:-2:2]
[10, 30, 50]#List elements at indexes -7,-5,-3 are shown.

9. Find number of elements in list


Function len() of Python returns number of elements in a list. The

syntax of len() is
len(listname)

listname refers to existing list whose length we want to fine.

Example

>>> classes=[‘xii’,’xi’,’x’,’ix’]
>>> len(classes)
4#Length of list classes is returned as 4 because there are four values in the list.

10. Membership operators on List


We can use ‘in’ and ‘not in’ operators with Lists

Example:

>>> list1=[10,20,30,40,50,60,70]

>>> 10 in list1
True #Output is True because 10 is contained in the list.

>>> 25 in list1
False #Output is False because 25 is not contained in the list.

>>> 25 not in list1


True #Output is True because 25 is not contained in the list.

>>> 20 not in list1


False #Output is False because 20 is contained in the list.

11. Concatenation Operator on List


We can concatenate two lists together by using concatenation operator

(+).
Example:

>>> list1=[11,22,33]
>>> list2=[40,50,60]

>>> list1+list2
[11, 22, 33, 40, 50, 60] #Elements of list1 and list2 are joined together in the
output

12. Replication Operator on List


We can use replication operator (*)to repeat a list.

Example:

>>> list1=[11,22,33]

>>> list1*2
[11, 22, 33, 11, 22, 33] #Elements of list1 are repeated twice in the output.

13. Comparison of Lists


We can compare two lists using relational operators of Python

If all elements are two lists are same, then two lists are considered

equal. Lists to be compared must be of same type.

Elements of list are compared one by one. If any comparison is

wrong, False is returned.


Example

>>>> list1=[11,22,33]
>>> list2=[11,22,33]
>>> list3=[12,23,34]
>>> list4=[12,25]
>>> list5=[12,23,33]

>>> list1==list2
True #Elements of list1 and list2 are same, So True is returned.

>>> list1<list2
False#Elements of list1 and list2 are same, So False is returned.

>>> list1<list3
True#All elements of list1 are less than list2, So True is returned.

>>> list1>list3
False#All elements of list1 are less than list2, So False is returned.

>>> list1<list4
True#Only first two elements of list1 are compared to list4. As first two
elements of list1 are less than first two elements of list4, True is returned.

>>> list3<list5
False#First two elements of list3 and list5 are same but third element of list3 is
not less than list5. So False is returned.
You must first complete Display output in Python 3 | print() function in Python 3
before viewing this Lesson

Python Tuple with Examples | Tuple


in Python 3
What is a Tuple in Python 3?
Tuple is a collection of values within pair of parenthesis. These values

must be separated by commas. These values can be of any data type.

Tuples are immutable i.e. we can’t modify the elements of a tuple.

1. Creating a Tuple in Python 3


To create a tuple, we can put multiple values within the pair of

parenthesis.

Syntax:

tuplename= (value1,value2,value3,……. valueN )

tuplename refers to name of tuple defined by the programmer.

( ) Pair of parenthesis specifies that it is a tuple.


value1, value2,value3, …. valueN are different values stored in the

tuple.

Examples:

( 1,2,3)
Tuple of integers

( 1,2.5,3,9.5 ) Tuple of numbers(integers and floating


point)

(‘a’,’b’,’c’ )
Tuple of characters

( ‘a’,1,’b’,3.5 )
Tuple of mixed values

(‘First’,’Second’ )
Tuple of strings

2. Creating an empty tuple in Python 3


E mpty tuple contains no element in it. It is equivalent of 0 or ‘

‘(blank). So it has truth value as False.

We can create an empty tuple in two ways:

a. By specifying an empty pair of square parenthesis


Tuple1=( )

Note: Tuple1 is an empty tuple containing no element in it.


b. By using tuple() function without anything within the pair of
parenthesis.
Tuple2= tuple ( )

Note: Tuple2 is an empty tuple containing no element in it.

3. Single Element Tuple in Python 3


If we give a single value within a pair of parenthesis, Python

considers it a single variable value

Example 1
>>>t=(1)

>>>print(t)

To create a tuple with one element, we need to add a comma after

single value within the pair of parenthesis:

Example 2
>>>t=3,

>>>print(t)

(3,)

Example 3
>>>t=(3,)

>>>print(t)

(3,)

4. Creating a Long Tuple in Python 3


If tuple contains many elements which are not able to fit on one line,

we can split it across several lines as given below:

tuple1=(10,20,30,40,50,60,70,80,90,100,

120,130,140,150)

Opening parenthesis appears in the beginning and closing parenthesis

appears at the end of tuple.

>>> tuple1=(10,20,30,40,50,60,70,80,90,100,

120,130,140,150)

>>> tuple1

(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150)

5. Nested tuple in Python 3


If one tuple is enclosed within another tuple, it is known as nested

tuple.
A tuple can contain another tuple as its element. Such a tuple is called

nested tuple

Example:
Tuple1=(1,2,(5,6,7),9)

Tuple1 is a nested tuple with four elements:3,4,(5,6,7)and9 .

Here (5,6,7) is nested tuple.

>>> tuple2=(1,2,(5,6,7),9)

>>> tuple2

(1, 2, (5, 6, 7), 9)

6. Creating a Tuple from Existing


Sequence in Python 3
We can use tuple() function to create tuple from existing sequences as

given below:

tuplename=tuple(<sequence>)

Here, tuplename refers to name of tuple specified by the programmer.

<sequence> refers to existing sequence object like string, tuple, set or

other tuple
Python Creates the individual elements of the tuple from the individual

elements of sequence.

Example 1:

Creating a tuple from existing string

>>> newtuple1=tuple('Lovejot')

>>> newtuple1

('L', 'o', 'v', 'e', 'j', 'o', 't')

Description

Tuple named newtuple1 is created from string ‘lovejot’


It converts each individual character of string into individual tuple elements:

(‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’)

Example 2:

Creating a tuple from existing list

>>> list1=[1,3,5,7,9]

>>> newtuple2=tuple(list1)

>>> newtuple2

(1, 3, 5, 7, 9)

Description
Tuple named newtuple2 is created from existing list list1 = [1,3,5,7,9]
It converts each individual element of list into individual tuple elements:

(1,3,5,7,9)

Example 3:

Creating a tuple from existing set

>>> s1={2,4,6,8,10}

>>> newtuple3=tuple(s1)

>>> newtuple3

(2,4, 6,8,10)

Description

Tuple named newtuple3 is created from existing set s1 = {2,4,6,8,10}


It converts each individual element of set into individual tuple elements:

(2,4,6,8,10)

7. Reading a Tuple from keyboard in


Python 3
We can also use tuple() function to read elements of a tuple by using

keyboard.

Example 1:
Reading tuple from keyboard

>>> tuple3=tuple(input('Enter tuple ='))

Enter tuple = India

>>> tuple3

('I', 'n', 'd', 'i', 'a')

Description

String India is entered from keyboard and it gets converted into tuple as (‘I’, ‘n’,
‘d’, ‘i’, ‘a’)

Example 2:

Reading tuple from keyboard

>>> tuple3=eval(input('Enter tuple ='))

Enter tuple = (1,3,4,5)

>>> tuple3

(1,3,4,5)

Description

Tuple name tuple3 is entered from keyboard as (1,3,4,5)


8. Accessing elements of a Tuple in
Python 3
Each element of a tuple has an index associated with it.

Elements of a Tuple are also indexed in two ways:

1. FORWARD INDEXING AS 0,1,2,3,…


2. BACKWARD INDEXING AS -1,-2,-3,…

Example
we have a tuple named tuple1=(10,30,40,50,60,99)

Elements of above tuple are indexed as follows:

Index of first element of Tuple is 0 (Forward Indexing) and -6

(Backward Indexing)

So we an access first element of above tuple as tuple1[0] or tuple1[-6]

Similary we can access last element of above tuple as tuple1[5] or

tuple1[-1].

Example
>>> classes=('xii','xi','x','ix')

>>> classes[0]

'xii'

#First element of tuple is shown

>>> classes[2]

'x'

#Third element of tuple is shown

>>> classes[-1]

'ix'

#Last element of tuple is shown

>>> classes[-3]

'xi'

#Second element of tuple is shown

9. Slicing of Tuple elements in Python 3


We can view specific values in a tuple by specifying the range of

indexes within the pair of parenthesis as:


Tuplename(First_index,Last_index,Gap).

Tuplename is the name of tuple whose values you want to view.

First_index refers to the starting index.

Last_index refers to ending index.

Gap refers to the gap in indexes

Example
>>> tuple1=[10,20,30,40,50,60,70)

>>> tuple1[0:3]

(10, 20, 30)

#Tuple elements at indexes 0,1,2 are shown.

>>> tuple1[2:6]

(30, 40, 50, 60)

#Tuple elements at indexes 2,3,4,5 are shown.

>>> tuple1[-6:-3]

(20, 30, 40)

#Tuple elements at indexes -6,-5,-4 are shown.

>>> tuple1[0:7:2]
(10, 30, 50, 70)

#Tuple elements at indexes 0,2,4,6 are shown.

>>> tuple1[-7:-2:2]

(10, 30, 50)

#Tuple elements at indexes -7,-5,-3 are shown.

>>> tuple1[::2]

(10, 30, 50)

#All tuple elements starting from index 0 onwards will be shown with a gap of 2

i.e.elements at indexes 0,2,4 are shown.

10. Find number of elements in tuple in


Python 3
Function len() of Python returns number of elements in a tuple. The

syntax of len() is

len(tuplename)

tuplename refers to existing tuple whose length we want to fine.

Example

Python Code

>>> classes=('xii','xi','x','ix')
>>> len(classes)

Description

Length of tuple classes is returned as 4 because there are four values in the
tuple.

11. Membership operators on Tuple in


Python 3
We can use ‘in’ and ‘not in’ operators with Tuples

Example:

>>> tuple1=(10,20,30,40,50,60,70)

>>> 10 in tuple1

True

#Output is True because 10 is contained in the tuple.

>>> 25 in tuple1

False
#Output is False because 25 is not contained in the tuple.

>>> 25 not in tuple1

True

#Output is True because 25 is not contained in the tuple.

>>> 20 not in tuple1

False

#Output is False because 20 is contained in the tuple.

12. Concatenation Operator on Tuple in


Python 3
We can concatenate two tuples together by using concatenation

operator (+).

Example:

>>> tuple1=(11,22,33)

>>> tuple2=(40,50,60)

>>> tuple1+tuple2
(11, 22, 33, 40, 50, 60)

#Elements of tuple1 and tuple2 are joined together.

>>> tuple1[0:2]+tuple2[1:3]

(11, 22, 50, 60)

#Elements of tuple1 at indexes 0,1 and elements of tuple2 at indexes 1,2 are

joined together.

It should be noted that only one tuples can be concatenated with

another tuple. Tuple can’t be concatenated with non tuple value.

Example:

(1,3)+4 will give error as tuple (1,3) is added to integer value 4.

13. Replication Operator on Tuple in Python 3


We can use replication operator (*)to repeat a tu ple.

Example:
>>> tuple1=(11,22,33,44)

>>> tuple1*2

(11, 22, 33, 44,11, 22, 33,44)

#Elements of tuple1 are repeated twice in the output.


>>> tuple1[0:2]*2

(11, 22,11, 22)

#Elements of tuple1 at indexes 0 and 1are repeated twice.

14. Comparison of Tuples in Python 3


We can compare two tuples using relational operators of Python

If all elements are two tuples are same, then two tuples are considered

equal. Tuples to be compared must be of same type.

Elements of tuple are compared one by one. If any comparison is

wrong, False is returned.

Example:

>>> tuple1=(11,22,33)

>>> tuple2=(11,22,33)

>>> tuple3=(12,23,34)

>>> tuple4=(12,25)

>>> tuple5=(12,23,33)

>>> tuple1==tuple2
True

#Elements of tuple1 and tuple2 are same, So True is returned

>>> tuple1<tuple2

False

#Elements of tuple1 and tuple2 are same, So False is returned

>>> tuple1<tuple3

True

#All elements of tuple1 are less than tuple2, So True is returned.

>>> tuple1>tuple3

False

#All elements of tuple1 are less than tuple2, So False is returned.

>>> tuple1<tuple4

True

#Only first two elements of tuple1 are compared to tuple4. As first two

elements of tuple1 are less than first two elements of tuple4, True is

returned.

>>> tuple3<tuple5
False

#First two elements of tuple3 and tuple5 are same but third element of

tuple3 is not less than tuple5. So False is returned.

15. Unpacking Tuples in Python 3


To Create a tuple from a set of values is called packing and creating

individual values from a tuple’s elements is called unpacking.

Syntax for unpacking in Python:

<variable1>,<variable2>,<variable3>,…=tuplename

Number of variables at left side of assignment must match the number

of elements in the tuple at right side.

Example
We Have A Tuple as t1=(1,3,5,6)

There are four elements in it .

To unpack it, we can write:

a,b,c,d=t1

First element of tuple will be assigned to variable a.


Second element of tuple will be assigned to variable b.

Third element of tuple will be assigned to variable c.

Fourth element of tuple will be assigned to variable d.

Example:

>>> t1=[1,3,5,6]

>>> a,b,c,d=t1

>>> print(a,b,c,d)

1356

Description

Value of a is printed as 1, b as 3, c as 5 and d as 6.

16. Deleting Tuples in Python 3


We can use del statement to delete an entire tuple. We can’t delete

individual elements of a tuple as they are immutable

For example, We have a tuple named t1=(1,3,5,9)

It can be deleted as

del t1

Example:
Python Code

>>> t1=[1,3,5,6]

>>del t1

>>> t1

Traceback (most recent call last):

File "<pyshell#11>", line 1, in <module>

t1

NameError: name 't1' is not defined

Description

If you try to print it, error message will be generated as tuple no longer
exists.

You must first complete Display output in Python 3 | print() function in Python 3
before viewing this Lesson

Tuple functions in Python | Tuple


methods in Python
1. len() method
This method returns number of elements in a tuple.

Syntax:

len(<tuple>)

<tuple> refers to user defined tuple whose length we want to find.

Example:
>>> T1=(10,20,30,40)

>>> len(T1)

#There are 4 element in tuple.

2. max()
This method returns largest element of a tuple. This method works

only if the tuple contains all values of same type. If tuple contains

values of different data types then, it will give error stating that mixed

type comparison is not possible:

Syntax :

max(<tuple>)

<tuple> refers to name of tuple in which we want to find maximum

value.

Example 1:

>>> T1=[10,20,30,40]

>>> max(T1)

40

# 40 is the maximum value in tuple T1.


Example 2:

>>> T2=['Sumit','Anil','Rahul']

>>> max(T2)

'Sumit'

#’Sumit’ appears as last member as per English dictionary.

Example 3:

>>> T3=['Sumit',10,'Anil',11,'Rahul',12]

>>> max(T3)

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

max(T3)

TypeError: '>' not supported between instances of 'int' and 'str'

#Maximum can’t be found in mixed values.

Example 4:

>>> max([3,4],(5,6))

Traceback (most recent call last):

File "<pyshell#0>", line 1, in <module>

max([3,4],(5,6))
TypeError: '>' not supported between instances of 'tuple' and 'tuple'

#Maximum can’t be found among tuple and tuples.

3. min()
This method returns smallest element of a tuple. This method works

only if the tuple contains all values of same type. If tuple contains

values of different data types then, it will give error stating that mixed

type comparison is not possible:

Syntax :

min(<tuple>)

<tuple> refers to name of tuple in which we want to find minimum

value.

Example 1:

>>> T1=[10,20,30,40]

>>> min(T1)

10

#10 is the minimum value.

Example 2:

>>> T2=['Sumit','Anil','Rahul']
>>> min(T2)

'Anil'

#’Anil’ appears first as per English dictionary.

Example 3:

>>> T3=['Sumit',10,'Anil',11,'Rahul',12]

>>> min(T3)

Traceback (most recent call last):

File "<pyshell#2>", line 1, in <module>

min(T3)

TypeError: '<' not supported between instances of 'int' and 'str'

#Minimum can’t be found in mixed values.

Example 4:

>>> min([3,4],(5,6))

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

min([3,4],(5,6))

TypeError: '<' not supported between instances of 'tuple' and 'tuple'

#Minimum can’t be found among tuple and tuples.

4. index()
This method is used to find first index position of value in a tuple. It

returns error if value is not found in the tuple.

Syntax:

Tuple.index (<Val>)

Tuple is user defined tuple.

<Val> refers to the value whose index we want to find in Tuple.

Example 1:

>>> T1=[13,18,11,16,18,14]

>>> print(T1.index(18))

#Index of first occurance of 18 is shown i.e. 1.

Example 2:

>>> print(T1.index(10))

Traceback (most recent call last):

File “<pyshell#2>”, line 1, in <module>

T1.index(10)

ValueError: 10 is not in tuple

# Above example shows error as 10 is not in the tuple


5. count()
This function is used to count and return number of times a value

exists in a tuple. If the given value is not in the tuple, it returns zero.

Syntax:

Tuple.count(<value>)

<value> refers to the value whose count we want to find.

Example 1:

>>> T1=[13,18,11,16,18,14]

>>> T1.count(18) #18 appears twice in tuple T1.

Example 2:

>>> T1=[13,18,11,16,18,14]
>>> T1.count(30)
0 #0 is the output as 30 doesn’t exist in the tuple T1.

6. tuple()
This method is used to create a tuple from different types of values.

Syntax:

Tuple(<sequence>)

<sequence> refers to a sequence type object that we want to convert to

a tuple.

Example 1 – Creating empty tuple


>>> t=tuple()

>>> t

()

Example 2 – Creating a tuple from a list

>>>t=tuple([1,2,3])

>>>t

(1,2,3)

Example 3 – Creating tuple from a string

>>>t=tuple(“abc”)

>>>t

(‘a’,’b’,’c’)

Example 4 – Creating a tuple from keys of a dictionary

>>> t1=tuple({1:'a',2:'b'})

>>>t1

(1,2)
You must first complete Display output in Python 3 | print() function in Python 3
before viewing this Lesson

Python Dictionary with examples


What is a dictionary?
A Dictionary is an unordered collections of elements in the form of

key: value pairs separated by commas within the pair of braces(curly

brackets).

Example:

{1:’a’,2:’b’,3:’c’}

Characteristics of a Dictionary
1. Unordered Set

Dictionary is an unordered set of key: value pairs i.e. Its values can

contain references to any type of object .

2. Not a Sequence

Dictionary is not a sequence because it is unordered set of elements.

Sequencs like list and string are indexed by a range of numbers. so

they are ordered but a dictionary is indexed by keys not numbers so it

is unordered collection.
3. Indexed by Keys, Not Numbers

Dictionaries are indexed by keys. A key can be any non mutable type.

So we can use strings numbers as well as tuples as keys as they are

non mutable.

Values in a dictionary can be of any type.

For example dictionary dict1 has keys of different immutable types:

>>> dict1={0:"numeric key","str":"string key",(4,5):"tuple key"}

>>> dict1

{0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}

4. Keys must be Uniqe

Keys within a dictionary must be unique. As keys are used to identify

values in a dictionary ,there cannot be duplicate keys in a dictionary.

Example:

>>> dict2={5:"number", "a":"string", 5:"numeric"}

>>> dict2

{5: 'numeric', 'a': 'string'}

If there are duplicate keys, key appearing later will be taken in the

output.
5. Mutable

Dictionaries are also mutable. We can change the value of a paricular

key using the assignment statement as:

<dictionary>[<key>]=<value>

Example

>>> dict1={0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}

>>> dict1['str']="STRING"

>>> dict1

{0: 'numeric key', 'str': 'STRING', (4, 5): 'tuple key'}

Value of key ‘str’ has been updated with ‘STRING’

f . Internally Stored as Mappings

The key: value pairs in a dictionary are associated with one another

with some internal function (called hash-function). This way of linking

is called mapping.
1. Creating a Dictionary in Python
To create a dictionary, we need to put key:value pairs within curly

braces.

Syntax for creating a dictionary:

<dictionary-name>={<key>:<value>,<key>:<value>…}

Elements of dictionary has two parts namely key followed by colon (:)

again followed by value. These key-value pairs are separated from

each other by commas.


Example:

Teachers ={“Lovejot”:”Computer science”,”Munish”:”Science”,


“Vijay”:”Punjabi”,”Sunil”:”SST”}

Braces (curly brackets) specify the start and end of the dictionary.

There are four key: value pairs. Following table shows the key- value

relationships in above dictionary.

Key–value pair Key Value

“Lovejot”:”Computer
Lovejot Computer
science”

“Munish”:”Science” Munish Science

“Vijay”:”Punjabi” Vijay Punjabi

“Sunil”:”SST” Sunil SST

Example

>>> Teachers ={"Lovejot":"Computer science", "Munish":"Science",


"Vijay":"Punjabi", "Sunil":"SST" }

>>> Teachers

{'Lovejot': 'Computer science', 'Munish': 'Science', 'Vijay': 'Punjabi',


'Sunil': 'SST'}
Keys of a dictionary must be of immutable types like string,number

etc.

If we try to give a mutable type as key, Python will give error

>>> dict={[1]:"abc"}

Traceback (most recent call last):

File "<pyshell#22>", line 1, in <module>

dict={[1]:"abc"}

TypeError: unhashable type: 'list'

TypeError:unhashable type means that we have tried to assign a key

with mutable type and Python dictionaries do not allow this.

2 . Initializing a Dictionary in Python


We can initialize a dictionary by writing key:value pairs collectively

separated by commas and enclosed in curly braces.

Example:

Employee ={‘name’:’john’,’salary’:10000,’age’:24}

3. Creating an empty Dictionary in


Python
There are two ways to create an empty dictionary:
(i) By giving dictionary contents in empty curly braces as:

Employee ={}

(ii) By using function dict() as:

Employee=dict()

Employee is an empty dictionary with no elements.

4. Creating a dictionary from name and


value Pairs in Python
We can create a new dictionary initialized from specified set of keys

and values. There are multiple ways to provide keys and values to

dict() function.

(a) Specify Key :Value pairs as keyword arguments to dict()

function

Keys and values are passed to dict() function in pair by using

assignment operator

Example:

>>> Employee =dict(name='Anil',salary=20000,age=25)

>>> Employee

{'name': 'Anil', 'salary': 20000, 'age': 25}

(b) Specify comma-separated key:value pairs


To specify values in key: value pairs, we need to enclose them in curly

braces while using dict() function.

Example:

>>> Employee =dict({'name':'Anil','salary':20000,'age':25})

>>> Employee

{'name': 'Anil', 'salary': 20000, 'age': 25}

(c) Specify keys separately and corresponding values separately.

Keys and values are enclosed separately in parentheses and are given

as arguments to zip() function ,which is given as an argument to dict()

function.

Example

>>> Employee =dict(zip(('name','salary','age'),('Anil',20000,25)))

>>> Employee

{'name': 'Anil', 'salary': 20000, 'age': 25}

In above example, ‘name’ is associated with value ‘Anil’, ‘salary’ is

associated with value 20000 and age is associated with value 25

(d) Specify Key:Value Pairs separately in form of sequences.


In this method, one list or tuple is passed to function dict() as

argument. This argument contains lists /tuple of individual key: value

pairs in the dictionary.

Example 1:

>>> Employee= dict([['name','John'],['salary',10000],['age',24]])

>>> Employee

{'name': 'John', 'salary': 10000, 'age': 24}

Example 2:

>>> Employee= dict((('name','John'),('salary',10000),('age',24)))

>>> Employee

{'name': 'John', 'salary': 10000, 'age': 24}

5. Accessing Elements of a Dictionary in


Python
To access elements from a dictionary, we use the keys defined in the

key: value pairs.

Syntax
<dictionary-name>[<key>]

To access the value corresponding to key “Lovejot “ in Teachers

dictionary, we can write Teacher[“Lovejot”]

Python will return

Computer Science

Similarly, following statement

>>>print (“Vijay teaches”,Teacher[‘Vijay’])

Will give output as:

Vijay teaches Punjabi

We can simply write the name of dictionary within the pair of

parenthesis after print() to display entire dictionary

Example

>>>>>> vowels={"Vowel1":"a","Vowel2":"e","Vowel3":"I","Vowel4":"o",
"Vowel5":"u"}

>>> vowels

{'Vowel1': 'a', 'Vowel2': 'e', 'Vowel3': 'I', 'Vowel4': 'o', 'Vowel5': 'u'}

>>> vowels['Vowel3']

I
Python gives error If we try to access a key that doesn’t exist

Consider the

Example

>>> vowels['Vowel6']

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

vowels['Vowel6']

KeyError: 'Vowel6'

Above error means that we can’t access the value of a particular key

that does not exist in dictionary.

6. Traversing a dictionary in Python


Traversing means accessing and processing each element of a

collection. We can use looping statements to traverse a dictionary.

The for loop makes it easy to traverse items in a dictionary as per

following syntax:

for<item>in<Dictionary>:

Process each item here


The loop variable <item>will be stored the keys of <Dictionary>one

by one which we can use inside the body of the for loop.

Example:

We have a dictionary dict1 as

Python Code

dict1={5:”number”, “a”:”string”, True:”Boolean”}

for key in dict1:

print (key,":",dict1[key])

Output

5 : number

a : string

True : Boolean

Description of above program

The loop variable key will be assigned the keys of the Dictionary

dict1,one at a time.

Using the loop variable which has been assigned one key at a time, the

corresponding value is shown along with the key using print statement

as
print(key,”:”,dict1[key])

During first iteration loop variable key will be assigned 5 so the key 5

and its value “number”will be printed.

In second iteration, key will get “a” and its value “string“will be

shown.

Similarly in third iteration, key will get True and its value “Boolean

will be shown”.

7. View all Keys of a dictionary in


Python
To view all the keys in a dictionary in one go, we can use dictionary>.keys()

function.

Example:

>>> dict1={5:"number", "a":"string", True:"Boolean"}

>>> dict1.keys()

dict_keys([5, 'a', True])

8. View all values of a dictionary in


Python
To view all the values in a dictionary in one go, we can use

dictionary>.values() function.

Example

>>> dict1={5:"number", "a":"string", True:"Boolean"}

>>> dict1.values()

dict_values(['number', 'string', 'Boolean'])

9. Adding Elements to Dictionary in


Python
We can add new elements to a dictionary using assignment operator

but the key being added should not exist in dictionary and must be

uniqe.

If the key already exists, then this statement will change the value of

existing key and no new entry will be added to dictionary.

<dictionary>[<key>]=<value>

Example

>>> Employee={'name': 'John', 'salary': 10000, 'age': 24}

>>> Employee['Dept']='Sales'
#Add new element with key=’Dept’, value=’Sales’

>>> Employee

{'name': 'John', 'salary': 10000, 'age': 24, 'Dept': 'Sales'}

10. Nesting of Dictionary in Python


We can also take one dictionary as an element of another dictionary.

This process of storing a dictionary inside another dictionary is called

nesting of dictionaries. We can store a dictionary as a value only not

as a key.

11. Updating Existing Elements in a


Dictionary in Python
We can change value of an existing key using assignment operators as:

Dictionary>[<key>]=<value>

Example

>>> dict1={0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}

>>> dict1['str']="STRING"

>>> dict1

{0: 'numeric key', 'str': 'STRING', (4, 5): 'tuple key'}

The key must exist in the dictionary otherwise new entry will be added

to the dictionary.
12. Deleting Elements from a
dictionary in Python
There are two methods for deleting elements from a dictionary.

(i) To delete a dictionary element using del command

We can use del command to delete an element of dictionary as.

del<dictionary>[<key>]

Example:

>>> Employee={'name': 'John', 'salary': 10000, 'age': 24}

>>> del Employee['name']

#Dictionary element with key ‘name’ gets deleted.

>>> Employee

{'salary': 10000, 'age': 24}

(i) To delete a dictionary element using pop() function

We can use pop() function to delete an element of dictionary as.

<dictionary>.pop(<key>)

Example
>>> Employee={'name': 'John', 'salary': 10000, 'age': 24}

>>> Employee.pop('name')

'John'

>>> Employee

{'salary': 10000, 'age': 24}

The pop () method deletes the key: value pair for specified key but

also returns the corresponding value.

If we try to delete key which does not exist, the Python returns error.

pop()method allows us to specify message to be shown when the given

key does not exist. It can be done as:

<dictionary>.pop(<key>,<Error-message>)

Example

>>> Employee.pop('new','Not Found')

'Not Found'

13. Check for Existence of a Key in


Python
We can use membership operators in and not in with dictionaries. But

they can check for the existence of keys only

To check for existence of existing key in a dictionary, we can write

statement as

<key> in <dictionary>

<key> not in <dictionary>

* The in operator will return True if the given key is present in the

dictionary otherwise False

* The not in operator will return True if given key is not present in the

dictionary otherwise False.

Example

>>> Employee={'name': 'John', 'salary': 10000, 'age': 24}

>>> 'name' in Employee

True

>>> 'name' not in Employee

False

You must first complete Display output in Python 3 | print() function in Python 3
before viewing this Lesson
Dictionary functions in Python |
Dictionary methods in Python
1. len()
This method counts and returns number of elements (key:value pairs)

in the dictionary.

Syntax

len(<dictionary>)

<dictionary> refers to the user defined dictionary whose length we

want to find.

Example 1:

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> len(emp)

Example 2:

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp['subject']='Mathematics'

>>> emp

{'name': 'Munish', 'age': 30, 'designation': 'Teacher', 'subject': 'Mathematics'}


>>> len(emp)

2. clear()
clear() method removes all items from the dictionary and the

dictionary becomes empty. This method does not delete the dictionary.

Syntax:

<dictionary>.clear()

<dictionary> refers to the user defined dictionary that we want to

clear.

Example 1:

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp.clear()

>>> emp

{}

To delete the dictionary we can use del statement along with

dictionary name.

Example 2:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> del emp

>>> emp

Traceback (most recent call last):

File "<pyshell#11>", line 1, in <module> emp

NameError: name 'emp' is not defined

#Error occurs as dictionary emp has been deleted

3. get()
We can use get() method get the item depending upon the key. If key

is not present in the dictionary, Python give error or does not display

anythin. We can also specify our own message through default

argument.

Syntax:

<dictionary>.get(key,[default])

<dictionary> refers to the user defined dictionary whose element we

want to get.

key refers to existing key of dictionary whose value we want to get. If

key does not exist , Python gives error. If default argument is

specified, value at the place of default is displayed.

Example 1:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp.get('age')

30

# emp.get(‘age’) returns 30 as 30 is the value corresponding to key age.

Example 2:

>>> emp.get('job','Key not found')

'Key not found'

# emp.get(‘job’) shows the message ‘Key not found’ as key ‘job’ doesn’t exist

in the dictionary.

4. items ()
This method returns all items of dictionary as a sequence of

(key,value) tuples. These are returned in no particular order.

<dictionary>.items()

<dictionary> refers to the user defined dictionary.

Example 1:

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> T1=emp.items()

>>> T1

dict_items([('name', 'Munish'), ('age', 30), ('designation', 'Teacher')])

>>> for i in T1:

print(i)

('name', 'Munish')

('age', 30)

('designation', 'Teacher')

Example 2:

As items() function returns a sequences of (key value) pairs, we can

write a loop having two variables to access key value pairs as.

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> T1=emp.items()

>>> for k,v in T1:

print(k,v)

name Munish

age 30
designation Teacher

#for Loop has two iteration variables key,value. For loop iterates through
each of the key-value pairs in the dictionary and assigns keys to loop
variable k and values to loop variable v at a time.

5. keys()
This method returns all the keys in the dictionary as a sequence of

keys (in form of a tuple). These are returned in no particular order.

Syntax:

<dictionary>.keys()

Example :

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp.keys()

dict_keys(['name', 'age', 'designation'])

6. values ()
This method returns all values from the dictionary as a sequence (a

tuple). These are returned in no particular order.

Syntax:

<dictionary>.values()

Example:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp.values()

dict_values(['Munish', 30, 'Teacher'])

7. update ()
This method merges key: value pairs from the new dictionary into the

original dictionary. If new dictionary contains same key as original

dictionary, key in the original dictionary gets overridden.

Syntax

<dictionary>.updates(<other-dictionary>)

Example:

>>> emp={'name':'Munish','age':30,'designation':'Teacher'}

>>> emp1={'name':'Rohit','Salary':40000}

>>> emp.update(emp1)

>>> emp

{'name': 'Rohit', 'age': 30, 'designation': 'Teacher', 'Salary': 40000}

Python Functions Tutorial | Using


Functions in Python 3
Using Functions in Python 3
Function is defined as the named group of statements which can be

used to perform a specific task. A function in Python can contain one

or more Python statements.

When we call a function, all the statements written within the function

body get executed on after another.

Click here for Quiz on Functions in Python


Advantages of a function in Python 3
 It is easy to locate and correct errors in a function.
 Function reduces complexity of a program.
 It is easy to perform testing of a program.
 They are used to divide a bigger problem into smaller sections.
 A function once defined can be used by other functions as well as
programs so a programmer can build a new application using
existing functions .
 It helps in avoiding repetition of code which saves time and
space.

Defining a function in Python


A function must be defined before it can be called within a program.

Syntax of a Function:

The syntax of a function is:

def Func_name(Arguments):

Local Variables
Statement_Block

return(Expression)

def specifies that a function definition is starting.

Func_name refers to the name of function defined by the programmer.

It should follow all the rules of a valid identifier of Python.

Arguments is the set of variables declared within the pair of

parenthesis after the function name.

Each of these variables are known as function arguments/parameters.

Arguments are used to receive values from another functions.

Local Variables: In this part, we declare local variables of function.

These variables are usable only within the function only.

These variables automatically get destroyed when program control

leaves the function. Indent must be given before local variables.

Statement-Block: It is set of valid Python statements which would

execute when we call the function within another function.

Indent must be given before statements that are part of Statement-

Block.

return is used when function returns some value. It appears with an

expression within a pair of parenthesis after it.


Indent must be given before return statement.

Expression: It is any valid expression of Python that is to be returned

by the function.

Program for defining function in Python

def message():

print("Hello Python")

def shownumber(num):

print(num)

Two functions namely message() and shownumber() have been defined


in above program.

Calling a Function in Python ( Using a


Function in Python)
A function can be called by specifying its name followed by the

required number of actual arguments separated by commas enclosed in

parenthesis.
If no arguments are required then there must be empty pair of

parenthesis after function name.

To call function message() defined above, we can write the following

statement

message()

Output

Hello Python

To call function shownumber() defined above, we can write the


following statement.

shownumber(10)

Output

10

On calling function shownumber(10), value 10 is sent as argument to


function. 10 will go and store in argument named num. Value of num
is displayed in function body.

Complete Program

Defining and calling function in Python


def message():

print("Hello Python")

def shownumber(num):

print(num)

message()

shownumber(10)

Output

Hello Python

10

You must first complete Python Functions Tutorial | Using Functions in Python 3
before viewing this Lesson

Types of function in Python 3


Python functions are categorized into three types:

1. Built-in Functions in Python


They are predefined functions provided by Python. They are also

known as library functions. These functions are basically used to

perform basic input/output operations and many other operations

which can’t be performed by any user defined function.

Built in functions can be called in any program The most commonly

used built in functions are input(), id(), type(), int(), float(), bool(),

len()etc.

2. Functions inside modules in Python


These functions are defined within modules and can be used only when

we import a particular module in our program.

For example, to use pre-defined functions sqrt(), we need to import the

module math as it contains definition of sqrt() function in it.

3. User defined function in Python


It is a function defined by a programmer depending upon his own

requirement. User defined functions are mainly defined for those

operations which are repeatedly required in a program.

A user defined function is a self contained group of statements which

can perform a specific task. Once a user defined function has been

defined, it can be called within another function in the same program

or another program.
A user defined function can also take values from other functions and

can also return some value.

There are two terms associated with functions:

Calling function: The function which calls another function within its

body is known as calling function.

Called function: The function which is called by another function is

known as called function. It is the called function which contains the

actual set of statements which would be executed when function call is

made.

Types of user defined function in Python


There are four types of user defined function in Python

(i) Function without parameters and without return


value
This type of function has no parameters so it doesn’t receive any

values from the calling function. So In we don’t specify anything

within the parenthesis written after the function name. This type of

function doesn’t contain return statement.

Features:
 Function contains no parameters.
 Calling function does not receive any value from the function.
 There is simple passing of control from calling function to called
function and vice versa but there is no passing of values between
them.
 Everything is performed within the body of function.

Program of function without parameters and without return value.

def sum():

a=int(input("Enter first number="))

b=int(input("Enter second number="))

c=a+b

print ("sum=",c)

sum() #Function sum() is called here

Output

Enter first number=2

Enter second number=3

sum= 5

Description of Above Program

In the above program, we have defined a user define function named

sum() which reads values of two variables, adds them and shows their

addition. This function has been called as sum().


(ii) Function with parameters and without return
value
In this type of function, we need to specify parameters within the

parenthesis written after the function name. parameter are generally

variables declared individually within the parenthesis.

Parameters within the parenthesis while defining a function are known

as formal parameters. Parameter within the parenthesis while calling

the user defined function are known as actual parameters.

The formal parameters receive values from actual parameters. This

function doesn’t return any value so we don’t write return statement.

Features:

 Function contains parameters.


 Calling function does not receive any value from the called
function.
 There is passing of values from calling function to user defined
function.
 Input is received from calling function and only manipulation is
performed within the user defined function.
 Click here for Quiz on Functions in
Python

Program of function with parameters and without return value.

def sum(a,b):
c=a+b

print ("sum=",c)

sum(10,5)

Output

sum= 15

Description of Above Program

In the above program, we have defined a user defined function named

sum() which has two formal parameters namely a and b. It performs

addition of a and b and shows their addition.

This function has been called as sum(10,5). 10 and 5 are actual

parameters. 10 will go to a and 5 will be go to b so their sum 15 will

be shown in the output.

(iii) Function with parameters and with return value


In this category of function, we need to specify formal parameters

within the parenthesis written after the function name.


In this type of function, input is generally received from calling

function and some manipulation is performed within the user defined

function and result of manipulation is returned back to the calling

function.

While calling such type of function, we need to assign function calling

statement to some variable or we can directly write function calling

statement within the print() function.

Features:

 Function contains parameters.


 We must need to write return statement.
 There is a two-way communication of values between calling
function as well as called function i.e. values are transferred
from calling function to called function and again some value is
returned back to the calling function.
 At a time only one value can be returned by this type of function.
 Input is received from calling function and after manipulation
within the user defined function, result is returned back to the
calling function.

Program of function with parameters and with return value.

def sum(a,b ):

c=a+b

return(c)
s=sum(3,5)

print("sum of 3 and 5 is",s)

print("sum of 5 and 6 is ",sum(5,6))

Output

sum of 3 and 5 is 8

sum of 5 and 6 is 11

Description of Above Program

In the above program, we have defined a user defined function named

sum() which has two formal parameters namely a and b. It performs

addition of a and b and returns their addition by statement return(c).

This function has been called twice. Firstly as s=sum(3,5). 3 goes to a

and 5 goes to b so their sum 8 is stored in variable c which will be

returned and be saved in variable s.

Function sum() is called again as print(“sum of 5 and 6 is

“,sum(5,6)) within print() function. 5 and 6 go to parameters a and b

respecitively. Their sum is returned and shown as 11


(iv) Function without parameters and with return
value
This category of function doesn’t contain any parameter.

Manipulations are performed within the body of user defined function

and result of manipulation is returned back to the calling function.

There is one way communication in this function i.e. value is

transferred from called function to calling function. While calling such

type of function, we need to assign function calling statement to some

variable or we can directly call function within the print function.

Features :

 Function doesn’t contain parameter.


 There is a one way communication of values between called
function and calling function i.e. values are transferred from
called function to calling function.
 All manipulations are performed within the user defined function
and result is returned back to the calling function.

Program of function without parameters and with return value.

def sum():

a=int(input("Enter first value="))

b=int(input("Enter second value="))

c=a+b

return(c)
s=sum()

print("Sum=",s)

print("Sum=",sum())

Output

Enter first value=2

Enter second value=3

Sum= 5

Enter first value=4

Enter second value=5

Sum= 9

Description of Above Program

In the above program, we have defined a user defined function named

sum() It performs addition two values after reading them and result is

returned back by statement return(c).

This function has been called twice. Firstly as s=sum(). Values of

variables a and b are input and their sum is stored in variable c which

will be returned and be saved in variable s.


Function sum() is called again as print(“sum =”,sum()) within print()

function. Values of variables a and b are input again and their sum is

stored in variable c which will be returned and shown.

You must first complete Python Functions Tutorial | Using Functions in Python 3
before viewing this Lesson

Types of function parameters in


Python
In Python, we can take four different types of parameters in a user

defined function. They are as follows:

1. Positional parameters in Python


A positional parameter is any parameter that’s not supplied as a

key=value pair.

Value of first actual parameter goes to first formal parameter, second

actual parameter goes to second formal parameter and so on as per

their positions.
In the following program, formal parameter a gets 25 and formal

parameter b gets 10.

Program to demonstrate positional parameters

def show(a,b):

print(a,b)

show(25,10)

#a gets 25 and b gets 10

Output

25 10

2. Passing string as function parameter


in Python
A string can be passed as a parameter to a Python function as like

other parameters. We simplay need to pass string value as actual

parameter while calling the function.


When we pass a string as argument, it is automatically passed by

value. Strings are immutable so no changes can be made to formal

parameter.

Program of function with string as parameter.

def show(var1):

print(var1)

show('Amit')

”’ Amit’ will be stored in formal parameter var1 and shown within function

body.”

Output

Amit

3. Passing list as function parameter in


Python
A list can also be passed as a parameter to a Python function. We

simply need to specify the name of list both as actual as well as formal

parameter. There is no need to specify brackets.


When we pass a list as an argument, it is automatically passed by

reference. Lists are mutable so changes be made to elements of list in

function body will direct affect actual parameters.

Example 1 – Program of function with list as parameter.

def show(list1):

print(list1)

L1=[10,20,30,40]

show(L1)

Output

[10, 20, 30, 40]

In the above program, L1 is the list passed as actual argument to function


show(), list1 is the formal parameter which will receive values of L1

Example 2- Program of function with list as parameter.

def show(list1):

list1[0]='a'
L1=[10,20,30,40]

show(L1)

print(L1)

Output

['a', 20, 30, 40]

In the above program, L1 is the list passed as actual argument to function


show(), list1 is the formal parameter which will receive values of L1.
First element of list1 i.e. list1[0] is assignmed ‘a’.

After the function call statement show(L1)

When we use print(L1) statement. It will display modified value of first

element of list i..e changes made to list1 are reflected back to list L1.

Click here for Quiz on Functions in Python


4. Passing tuple as function parameter in
Python
A tuple can also be passed as a parameter to a Python function. We

simply need to specify the name of tuple both as actual as well as

formal parameter. There is no need to specify parenthesis.

Tuples are immutable so we can’t make changes to tuple in formal

argument.
Example – Program of function with tuple as parameter.

def show(tuple1):

print(list1)

T1=[10,20,30,40]

show(T1)

Output

[10, 20, 30, 40]

In the above program, T1 is the list passed as actual argument to function


show(), tuple1 is the formal parameter which will receive values of T1 .

5. Passing dictionary as function


parameter in Python
A dictionary can also be passed as a parameter to a Python function.

We simply need to specify the name of dictionary both as actual as

well as formal parameter. There is no need to specify braces.

When we pass a list as an argument, it is automatically passed by

reference. Lists are mutable so changes be made to elements of list in

function body will direct affect actual parameters.


Program of function with list as parameter.

def show(dict1):
print(list1)D1={1:’a’,2:’b’,3:’c’}
print(D1)

Output

{1: 'a', 2: 'b', 3: 'c'}

In the above program, dictionary D1 is passed as actual argument to


function show(), dict1 is the formal parameter which will receive values of
D1.

6. Default parameters in Python


In default parameters, we can assign some value to the formal

parameters of a function but the assignment of values is possible from

last argument of the function towards left.

The main use of default parameters is that we may or may not provide

value for default parameter while calling the function because function

will automatically take the default value of formal parameter in the

function.

Example: def show(a=5,b=10)

In the above example, a is a default parameter having value 5 and b is

also a default parameter having value 10.


Example-1 : Program of function without default parameters.

def show(a=5,b=10):

print(a,b)

show() #a takes 5, b takes 10

show(25) #a takes 25, b takes 10

show(25,40) #a takes 25, b takes 40

Output

5 10

25 10

25 40

Example-2 Program of function without default parameters.

def display(fname,lname="Kumar"):

print(fname,lname)
display("amit") #fname gets 'amit', lname gets 'Kumar'

display("amit","singh") #fname gets 'amit', lname gets 'singh'

Output

amit Kumar

amit singh

7. Required parameters in Python


In case of Required parameters, number and order of actual parameters

and formal parameters must be same. The values of actual parameters

are assigned to formal parameters on one to one basis i.e. First actual

parameter in assigned to first formal parameter, second actual

parameter in assigned to second formal parameter and so on.

Program of function with Required parameters.

def show(name,salary):

print(name,salary)

show('Amit',50000)
Output

Amit 50000

8. Keyword arguments in Python


The keyword parameters are used to specify the names of formal

parameters while calling the function. The main advantage of

keywords parameters is that we can write actual parameters in any

order we want.

Values of actual parameters will be passed to formal parameters on the

basis of their names rather than their order.

Program of function with Keyword parameters.

def show(name,age,salary):

print("name=",name)

print("age=",age)

print("salary=",salary)

show(age=30,salary=50000,name='Amit')
”’value of age will be 30 in formal parameter age,

name will receive ‘Amit’ and

salary will recieve 50000.”’

Output

name= Amit

age= 30

salary= 50000

9. Variable number of parameters in


Python
This technique of passing parameters to a function is very useful when

we do not know the exact number of parameters that will be passed to

a function. Syntax of function with variable number of parameters is:

def func_name(var1, *vartuple)

Here var1 takes very first parameter value. All parameter values

passed after first parameter will be stored in *vartuple in the form of a

tuple. We can perform operations on these values just as we work with

tuples.

Program of function with variable number of parameters.

def show(var1,*var2):
print(num1)

print(var2)

show('Amit',1,3,4,5,6)

‘Amit’ will be stored in argument var1. Values 1,3,4,5,6 will be stored as a

tuple in var2.

Output

Amit

(1, 3, 4, 5, 6)

Python Modules and Packages


Python module is defined as a collection of functions, variables, constants,

classes, objects along with Python statements.

Click here for Quiz on Modules and Packages

Structure of a Python Module


A Python module is a normal Python file (.py file) that can contain

following things:

(i) Docstring
Docstring is text written within the pair of triple quotes. it is basically

used for documentation purpose. Docstring should be the first string

stored inside a module, function or class.

General conventions for Doctstring are:

1. First letter of first line is a capital letter.


2. Second line is blank line.
3. Rest of the details begin from third line.

(ii) Variables and constants


We can also define variables and constants inside a Python module

depending upon the requirement.

(iii) Class
We can also create more than class inside a Python module. Class may

be defined as blueprint for creating objects.

(iv) Object
Object is anything having properties and behaviour. But in Python,

object is just a variable of class type which canbe used to refer to

members of a class. It is also known as instance of class.

(v) Statements
We can write all valid statements of Python within a module.

(vi) Functions

Function is defined as named group of instructions. When we call

function, all statements written inside the function body get executed.
Types of Module in Python
There are two types of modules in Python

 Predefined modules
 User Defined Modules

(i) Predefined Modules in Python


Predefined modules are also known as library modules. They contain

library functions and classes provided by Python. These modules are

used to perform basic complex mathematical operations and many

other operations which can’t be performed by any user defined

modules. We can import predefined modules in any Python program.

(ii) User Defined Modules in Python


User Defined Modules are defined by a programmer depending upon

his own requirement. Once a user defined module is defined, it can be

called within another Python module or program.

Example

Module1.py
'''

Name: Demonstration of Python modules

What it contains: It contains two functions namely sum() and subtract()

'''

def sum(a,b):

return(a+b)

def subtract(a,b):

return(a-b)

In above example a user defined module named Module1.py has been

created.

We can see documentation of above program by using following

command at python shell.

1. import Module1 #to import module

2. help(Module1) #To see documentation of module

>>> import Module1

>>> help(Module1)

Help on module Module1:

NAME
Module1

FILE

c:\python30\Module1.py

DESCRIPTION

Name: Demonstration of Python modules

What it contains: It contains two functions namely sum() and subtract()

FUNCTIONS

subtract(a, b)

sum(a, b)

We can also use predefined function dir() to see list of elements

defined inside a module as follows:

>>>import Module1

>>> dir(Module1)

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'subtract',


'sum']

Importing Modules in a Python Program


Before using functions and other components of a module in a Python

program, we need to import the module in our program.


We can use import statement to import modules in a program. The

import statement can be used in two ways:

 To import entire module: the


 To import selected objects

(i) To import entire Python module


We can use import<module-name>command to import entire module.

The import statement internally executes the code written inside

module file and then makes it available to our program.

Syntax to import entire module is:

import module1[, module2[,…module3]]

module1,module2,module3 refer to names of different modules that we

want to import in our program.

Example1:

To import predefined module math in a Python program we can use

import math statement in a Python program.

Example2 :

To import user defined module Module1 in a Python program we can

use import Module1 statement in a Python program.

Example3:
To import predefined modules math and random in a Python program

we can use import math.randome statement in a Python program.

After importing a module, you can use any function or other element

of the imported module as per following syntax:

<module-name>.<function-name>()

Example1:

To call sqrt() function defined in module math, we can write

math.sqrt() statement in Python program.

Example2:

To call sum() function defined in module Module1, we can write

Module1.sum() in Python program.

(ii) To Imported Select Objects from a


Python module
If you want to import some selected items, not all from a module, then

you can use from <module> import statement as per following syntax:

from<module>import<objectname>[,<objectname>[…]|*

To import a single object from a module we don’t have to prefix the

module’s name, we can write the name of object after keyword import.
For example to import just the constant pi from module math, you can

write:

from module math import pi


Now, we can use the constant pi. We need not prefix it with module

name. We can simply write print(pi) statement at Python shell to get

value of pi.

To import multiple objects from a module we don’t have to prefix the

module’s name, we can write the comma separated list of objects after

keyword import.

For examle, to import functions sqrt() and pow() from math module,

we need to write from module math import sqrt, pow

To import all the items from a module we don’t have to prefix the

module’s name, we can write:

from<modulename>import *

To import all the items in module math,we can write:

from math import *

Now, we can use all the functions, variables etc from math module,

without having to prefix module’s name to the imported item name.


Example 1

Program to import and use module Module1.py in program.

import Module1

print(Module1.sum(10,5))

print(Module1.subtract(10,5))

Output

15

Example 2

Program to import and use math module in program.

import math

print(math.sqrt(9))

print(math.pow(2,3))

Output

3.0
8.0

Example 3

Program to import and use specific functions of math module.

from math import sqrt,pow

print(sqrt(9)) #No need to prefix math

print(pow(2,3))

Output

3.0

8.0

Example 4

Program to import all functions of module math.

from math import *

print(sqrt(9)) #No need to prefix math

print(pow(2,3))

Output

3.0
8.0

Processing of Import <module> Command


When we use import <module> command, internally following things

take place:

 The code of imported module is interpreted and executed.


 Defined functions and variables created in the module are now
available to the program that imported module.
 For imported module, a new namespace is setup with the same
name as that of the module.

Namespace in Python is a named environment containing logical

grouping of related objects. For every module(.py file), Python creates

a namespace having its name similar to that of module’s name.

For example after importing module Module1 in our program ,all

objects of module Module1 would be referred as Module1.<object-

name>.

Example: if Module1 has a function defined as sum(), then it would be

referred to as Module1.sum() in our program.

When we issue from <module> import <object> command, internally

following things take place:

 The code of imported module is interpreted and executed.


 Only the asked functions and variables from the module are made
available to the program.
 No new namespace is created, the imported definition is just
added in the current namespace.
 That means if your program already has a variable with the same
name as the one imported via module, then the variable in your
program will hide imported member with same name because
there cannot be two variables with the same name in one
namespace. Following code fragment illustrates this.

Mathematical functions in python |


math module in python
Python has a variety of predefined functions . We do not need to

import any module for them. So we use these functions of Python

directly as: <function-name>()

Example: input(), int(), float(), type(), len() etc. are predefined

functions.

Consider the following example program that uses some built-in

functions of Python.

Working with math Module in Python


Python has a predefined module named math having list of predefined

functions to do mathematical calculations

To work with functions of math module, we need to first import it by

using statement as:

import math
Following table lists some useful math functions:

Function Syntax Description Example

This function returns


base raised to power
exp.
Error occurs if (base=0
pow math.pow(base,exp) math.pow(2,3) gives 8
and exp<=0) or (base<0

and exp is not integer).

math.ceil(1.3) gives
2.0
This function returns math.ceil(-1.3) gives -
ceil math.cell(num)
next integer value.
1.0

math.floor(1.3) gives
1.0
This function returns math.ceil(-1.3) gives -
floor math.floor(num)
previous integer value.
2

This function returns the math.sqrt(16.0) gives


square root of a 4.0.
sqrt math.sqrt(num) number. If number is
less than 0, error will be
shown.

exp() function returns e math.exp(2.0) gives


exp math.exp(num)
raised to the power exp. the value of e 2 .

fabs math.fabs(num) fabs() function returns math.fabs(1.0) gives


the absolute value of 1.0.
num.
Negative value is
math.fabs(-1.0) gives -
converted to positive
1.0.
value.

math.log(1.0) gives
the natural logarithm
for 1.0.
log() function returns
the natural logarithm for
log math.log(num,[base]) num. math.log(-1.024, 2)
Error occurs if num<=0
will give logarithm of

1024 to the base 2.

log10() function returns


the base 10 logarithm math.log10(1.0) give
log10 math.log10(num) for num. base 10 logarithm for
Error occurs if num <=0. 1.0.

sin() function returns math.sin(val)


the sine of arg. The (val is a number)
sin math.sin(arg)
value of arg must be in
radians

cos() function returns math.cos(val)


the cosine of arg. The (val is a number)
cos math.cos(arg)
value of arg must be in
radians

tan() function returns math.tan(val)


the tangent of arg. The (val is a number)
tan math.tan(arg)
value of arg must be in
radians

degrees() converts angle


math.degrees(3.14)
degrees math.degrees(x) x from radians to
would give 179.91.
degrees.
radians() converts angle
math.radians(179.91)
radians math.radians(x) x from degrees to
would give 3.14.
radians.
math.pi gives the value of mathematical constant pi=3.141592.

math.e gives the mathematical constant e=2.718281.

Mathematical functions at Python shell

>> import math

>> print(math.pow(2,3))

8.0

>>> print(math.ceil(3.4))

>>> print(math.floor(3.4))

>>> print(math.sqrt(16))

4.0

>>> print(math.exp(2))

7.38905609893065

>>> print(math.fabs(-2.5))
2.5

>>> print(math.log(15))

2.70805020110221

>>> print(math.log(15,2)) #log base 2

3.9068905956085187

>>> print(math.log10(15)) #log base 10

1.1760912590556813

>>> print(math.sin(30))

-0.9880316240928618

>>> print(math.cos(30))

0.15425144988758405

>>> print(math.tan(30))

-6.405331196646276

>>> print(math.degrees(3.14))

179.9087476710785

>>> print(math.radians(30))

0.5235987755982988

>>> print(math.pi)

3.141592653589793

>>> print(math.e)
2.718281828459045

Program to calculate area of a triangle using Heron’s formula

import math

a=float(input("Enter side1 of triangle:"))

b=float(input("Enter side2 of triangle:"))

c=float(input("Enter side3 of triangle:"))

s=(a+b+c)/2

area=math.sqrt(s*(s-a)* (s-b)* (s-c))

print("area of triangle is:", area)

Output

Enter side1 of triangle:2


Enter side2 of triangle:3
Enter side3 of triangle:4
area of triangle is: 2.9047375096555625

Program to find roots of a quadratic equation

import math

a=float(input("Enter value of a="))

b=float(input("Enter value of b="))


c=float(input("Enter value of c="))

r1=(-b+math.sqrt(b*b-4*a*c))/(2*a)

r2=(-b-math.sqrt(b*b-4*a*c))/(2*a)

print("root1=", r1)

print("root1=", r2)

Output

Enter value of a=2


Enter value of b=6
Enter value of c=3
root1= -0.6339745962155614
root1= -2.3660254037844384

random module in python 3 |


generate random number in python
3
Python has a predefined module random that provides random-number

generator functions. A random number is a number generated

randomly.

To use random number generator functions in our Python program, we

first need to import module random by using import statement as:

import random

There are three random number generators functions in Python as


 random()
 randint()
 randrange()

i. random()
It returns a random floating point number in the between 0.0 and 1.0

(0.0, 1.0)

Number generated with random() will always be less than 1.0.

Example 1:
>>> import random

>>> print(random.random())
0.13933824915500237 #It will produce a different random value when we run it.

Example 2:
>>> import random

>>> print(random.random()*10) #Value generated between 0 and 10

9.857759779259172

ii. randint(a, b)
it returns a random integer number in the range (a, b). a and b are both included

in the range.

Example:
>>> import random

>>> print(random.randint(2,6))

#It may produce a different random value between 2 and 6.

iii. randrange(start,stop,step)
it returns a random integer number in the range start and stop values, both are

included in the range. We can also give step size in this function

Example 1:
>>> import random
>>> print(random.randrange(6))

#It may produce a different random value between 0 and 6.

Example 2:
>>> import random

>>> print(random.randrange(2,6))

#It may produce a different random value between 2 and 6.

Example 3:
>>> import random

>>> print(random.randrange(1,7,2)) #2 is the step size.

#It may produce a different random value among 1,3,5,7.

statistics module in python 3 |


statistical functions in python 3
Python has a predefined module statistics that provides statistical

functions.

To use statistical functions in our Python program, we first need to

import module statistics by using import statement as:


import statistics

Most commonly used functions of this module are:

 mean()
 mode()
 median()

i. mean()

This function is used to find average value from a sequence of values.

It can be used to find mean of values from list, tuple as well as

dictionary.

** Commands tried using spyder

>>>import statistics

>>>list1=[1,3,4,5,4]

>>>print(statistics.mean(list1))

3.4

#Average of values contained in list1=[1,3,4,5,4]

>>> t1=(1,3,4,5,4)

>>> print(statistics.mean(t1))

3.4

#Average of values contained in tuple t1=[1,3,4,5,4]

>>>d1={1:'a',3:'b',5:'c'}
>>>print(statistics.mean(d1))

#Average of values contained in dictionary d1=[1,3,4,5,4]

ii. mode()
This function is used to find value having occurrence for largest

number of times. It can be used to find mode of values from list and

tuple.

>>>import statistics

>>>list1=[1,3,4,5,4]

>>>print(statistics.mode(list1))

#4 occurs maximum number of times in the list list1.

>>>t1=(1,3,4,5,4)

>>>print(statistics.mean(t1))

#4 occurs maximum number of times in the tuple t1.

iii. median()
This function is used to find median value from a sequence of values.

It can be used to find median of values from list, tuple as well as


dictionary. When the number of data items is odd, the middle value is

returned.

When the number of values are even, the median is calculated by

taking the average of the two middle values.

>>>import statistics

>>>list1=[1,3,4,5,4]

>>>print(statistics.median(list1))

#4 appears in the middle of list.

>>>t1=(1,3,4,5)

>>>print(statistics.mean(t1))

3.5

#Average of tuple values at positions 2 and 3 i.e. 3 and 4.Average of 3 and 4 is

3.5

>>>d1={1:'a',3:'b',5:'c'}

>>>print(statistics.mean(d1))

#3 is the middle element of dictionary.

Steps to create data file in python


1. Opening a file
Before working with data files in Python, the first thing is to open the

file. We can use open( ) function to do it as:

Syntax:

<file_object> = open(<filename>)

OR

<file_object> = open(<filename> , <mode>)

<file_object> is the file object used to read and write data to a file on

disk. File object is used to obtain a reference to the file on disk and

open it for different tasks.

<mode> is the file opening mode used to specify the operation we want to

perform on file.

Different Modes to Open file are

Read only
[File must exist otherwise I/O error is
‘r’
generated ]

‘w’ Write only

 If the file does not exist, file is


created.
 If file exists, Python removes
existing data and writes new data
in the file.

Append

 If the file does not exist, file is


‘a’ created.
 If file exists, Python will write
new data at end of the file.

Read only

 File must exist otherwise I/O


‘r+’ error is generated.
 Both reading and writing of data
can be done.

Write and Read

 If the file does not exist, file is


created.
 If file exists, Python removes
‘w+’
existing data and writes new data
in the file.
 Both reading and writing of data
can be done .

Write and Read

 If the file does not exist, file is


created.
‘a+’  If file exists, Python will write
new data at end of the file.
 Both reading and writing of data
can be done .

Read only in binary mode


[File must exist otherwise I/O error is
‘rb’
generated ]
Write only in binary mode

 If the file does not exist, file is


created.
‘wb’
 If file exists, Python removes
existing data and writes new data
in the file.

Append in binary mode

 If the file does not exist, file is


‘ab’ created.
 If file exists, Python will write
new data at end of the file.

Read and Write in binary mode


‘rb+’  File must exist otherwise I/O
‘r+b’ error is generated.
 Both reading and writing of data
can be done.

Write and Read in binary mode

 If the file does not exist, file is


‘wb+’ created.
‘w+b’  If file exists, Python removes
existing data and writes new data
in the file.
 Both reading and writing of data
can be done .

Write and Read in binary mode

 If the file does not exist, file is


‘ab+’ created.
‘a+b’  If file exists, Python will write
new data at end of the file.
 Both reading and writing of data
can be done .

Opening files in Read Mode


Example 1

file1 = open(“data.txt”)

OR

file1 = open(“data.txt”, "r")

Above statements open text file “data.txt” in read mode and

attaches it to file object file1.

Example 2

file2 = open (“d:\\data.txt”)

OR

file2 = open (“d:\\data.txt”, “r”)

Above statements open text file “data.txt” stored in d: drive in read

mode and attaches it to file object file2.

** We can also use single slash in the path but that may generate error

as Python also provides escape sequences like \t, \n, \b etc.

Example 3

file3 = open (“d:\files\data.txt”)

OR

file3 = open (“d:\files\data.txt”, “r”)


Above statements open text file “data.txt” stored in d:\files folder in

read mode and attaches it to file object file3.

** We can also use single slash in the path but that may generate error

as Python also provides escape sequences like \t, \n, \b etc.

2. Reading or writing data in the file


We can write and read data from data files by using different predefined

functions of Python. different functions to read and write data in Python are:

 write()
 read()
 readline()

3. Closing the file


We need to close file after performing required operations on it. Function fclose(

) can be used to close the file.

Syntax of fclose() function is:

<file_object>.close();

Example:

file1.close()

Writing content into a file in python


Different predefined functions of C language for writing content into

file are:
There are two predefined functions provided by Python to write data

into a data file

1. write()
write() function is used to write content into a data file.The syntax of

write() function is:

<fileobject>.write(str)

Here fileobject is the object that is linked to a data file in which we

want to write some content.

str refers to string variable of constant whose value we want to write

into data file.

**Before using write() function, file must be opened in write mode or

append mode.

Example 1

file1=open("data.txt","w")

file1.write("This is a file")

file1.close()

#Above code will create a new file data.txt and write “This is a file”

into the file.

Example 2
file2=open("data1.txt","w")

file2.write("This is line 1")

file2.write("\nThis is line 2")

file2.write("\nThis is line 3")

file2.close()

#Above code will create a new file data2.txt and write following three
lines int the file.

This is line 1

This is line 2

This is line 3

into the file.

Example 3
file3=open("data3.txt","w")

print("Enter three names")

for i in range(3):

name=input('Enter name')

file3.write(name + '\n' )

file3.close()

Output

Enter three names


Enter nameaman

Enter namesuman

Enter nameraman

#Above code will create a new file data3.txt and write following three

names into the file.

aman, suman and raman

2. writelines()
writelines() function is also used to write content into a data file.The

syntax of writelines() function is:

<fileobject>.writelines(List)

Here fileobject is the object that is linked to a data file in which we

want to write some content.

List refers to a List whose values we want to write into data file.

**Before using writelines() function, file must be opened in write

mode or append mode.

Example 1

file5=open("data5.txt","w")

L1=['amit','sumit','vijay']

file5.writelines(L1)
file5.close()

#Above code will create a new file data5.txt and write three values

contained in list i.e. ‘amit’, ‘sumit’ ,’vijay into the file.

Example 2
file6=open("data6.txt","w")

L1=[]

print("Enter three names")

for i in range(3):

name=input('Enter name')

L1.append(name+"\n")

file6.writelines(L1)

file6.close()

Output

Enter three names

Enter nameaman

Enter namesuman

Enter nameraman

# Above code allow you to enter three names and append entered

values into llist named L1 and insert values contained in list L1 i.e.

aman, suman and raman into file data6.txt.


Appending data into a File
When we open a file in “w” (write mode), Python creates a new file.

If file already exists, it will overwrite the file with new contents.

If we want to write data into the file while retaining the old data, then

we can open the file in append mode by using “a”, ,”w+” or “r+” .

Reading data from a file in python


Different predefined functions of Python to read data from file are::

1. read() method in Python


This function is used to read entire content of file or specific number of

characters from file.

Syntax 1:

<file_object>.read()

Here file_object is the name of file handler object that is linked to a data file.

Example:
#Python Program to display entire content of
text file data.txt
file1 = open(“data.txt”) #data.txt contains: I am a student

s=file1.read()

print(s)

Output
I am a student

** Above code will display contents of data file data,txt

Syntax 2:

<file_object>.read(N)

Here file_object is the name of file handler object that is linked to a data file.

N specified number of characters to be read from file.

Example:

file1 = open(“data.txt”) #data.txt contains: I am a student

s=file1.read(6)

print(s)

Output

I am a

** Above code will display first six characters (including spaces) from data file data.txt

2. readline() method in Python


This function is used to read single line at a time from an existing data file.

Syntax:

<file_object>.readline()

Here file_object is the name of file handler object that is linked to a data file.

Example 1:
#Python Program to display first line from
text file data1.txt
Data file data1.txt contains following data:

This is a data file

It contains data about a student

Name of student is Amit

file1 = open(“data1.txt”)

s=file1.readline()

print(s)

Output

This is a data file

** Above code will display first line from data file data1.txt

Example 2:
#Python Program to display data from text
data1.txt line wise.
f=open("data1.txt","r")

s=" "

while s:

s=f.readline()

print(s)

f.close()

Output
This is a data file

It contains data about a student

Name of student is Amit

** Above code will display complete data from file one line at a time from file data1.txt

3. readlines() method in Python


This function is used to read entire content from data file and store it in the form

of a list. Each line of data file would be stored as list element.

Syntax:

<file_object>.readlines()

Here file_object is the name of file handler object that is linked to a data file.

Example:

Data file data1.txt contains following data:

This is a data file

It contains data about a student

Name of student is Amit

Example 1:
Program to demonstrate the use of
readlines() method in Python.
file1 = open(“data1.txt”)

s=file1.readlines()

print(s)
Output

['This is a data file\n','It contains data about a student\n','Name of student is Amit\


n']

** Above code will display data from data file data1.txt in the form of a list.

Example 2:
Python program to display the number
of lines in a text file by using readlines()
method in Python.
file1 = open(“data1.txt”)

s=file1.readlines()

count =len (s)

print (“Number of lines=”, count)

file1.close( )

Output

Number of lines=3

** Above code will display number of lines in data file data1.txt .

flush ( ) method in Python


When we write data into a file , Python keeps everything temporarily in buffer

and saves it to actual file when close() function is called.

By using flush( ) function we can force Python to write the contents of buffer to

the actual file on storage .

The syntax to use flush( ) function is :


<fileObject>. flush ( )

#Python program to demonstrate the use


flush() method in Python
f = open ('newfile.txt', 'w+')

f.write ('Line 1')

f.flush( )

f.write ('Line 2')

f.flush( )

f.close( )

Other Programs
1. Python Program to read roll number
and name of a students and store these
details in a data file called “Marks.txt”.
Fileout = open ("Marks.txt", "a")

rollno= int (input("Enter Rollno="))

name= input ("Enter Name=")

record =str (rollno)+ "," + name + "\n"

Fileout.write(record)

Fileout.close( )
Output

Enter Rollno=101

Enter Name=aman

** Above code will read values of variables rollno and name and save it into data file

Marks.txt in comma separated format. File has been opened in append mode i.e new

records will be saved in the file at the end of existing file .

2. Python Program to display data saved


in data file “Marks.txt” one line at a
time.
Fileinput = open ("Marks.txt", "r")

s=" " #Blank space stored in string variable s.

while s :

s = Fileinput.readline( ) #Read one line at a time

print(s)

Fileinput.close ( )

Output

101,aman

3. Python Program to display data saved


in data file data1.txt one word at a time.
Fileinput = open ("data1.txt", "r")

s=" "

while s :
s = Fileinput.readline( ) #Read a line from file

words=s.split() #break line into a list or words

for w in words: #Read one word at a time from list

print(w)

Fileinput.close ( )

Output

This

is

data

file

It

contains

data

about

student

Name

of

student

is
Amit

4. Python Program to count number of


words in text file data1.txt
Fileinput = open ("data1.txt", "r")

s=" "

count=0

while s :

s = Fileinput.readline( ) #Read a line from file

words=s.split() #break line into a list or words

for w in words: #Read one word at a time from list

count+=1

print("Number of words=",count)

Fileinput.close ()

Output

Number of words= 16

5. Python Program to count number of


characters in data file data1.txt
Fileinput = open ("data1.txt", "r")

s=" "

count=0

while s :

s = Fileinput.read(1) #Read one character at a time.


count+=1

print("Number of characters=",count)

Fileinput.close ()

Output

Number of characters= 78

6. Python Program to count number of


vowels and consonants in data file
data1.txt
Fileinput = open ("data1.txt", "r")

s=" "

count=0

count1=0

while s :

s = Fileinput.read(1) #Read one character at a time.

if s in ['a','e','i','o','u']:

count+=1

else:

count1+=1

print("Number of vowels=",count)

print("Number of consonants=",count1)

Fileinput.close ()

Output
Number of vowels= 25

Number of consonants= 53

7. Python Program to add details of two


students’ to the data file Marks.txt
Fileout = open (“Marks.txt”, “a”)

for i in range (2) :

print (“Enter details for student”, (i+1), “below :”)

rollno = int(input(“Enter rollno=”))

name= input (“Enter Name=”)

marks=float (input(“Enter Marks=”))

rec =str(rollno)+”,”+ name +”,”+ str(marks)+’\n’

Fileout.write(rec)

Fileout.close( )

Output

>>>

Enter details for student 1 below :

Enter rollno :17

Name : Amit

Marks : 74.6

Enter details for student 2 below :

Rollno : 18
Name : John

Marks : 99.2

8. Python Program to read and display


details of students’ stored in data file
Marks.txt .
Fileinp = open (“Marks.txt”, “r”)

while str :

str = fileinp.readline( )

print(str)

Fileinp.close ( )

Output

>>>

17,Amit , 74.6

18, John , 99.2

Working with binary file in Python


Python provides the pickle module to write and read data from binary files. To

work with the pickle module, we need to import it in our program using import

statement as: import pickle

We can use dump( ) and load ( ) methods of pickle module to write and read

from a binary file respectively.


Steps to work with a binary file in
Python:
1. Import pickle module
We need to write import statement at the start of program to import pickle

module as:

import pickle

2. Open binary file in the required file mode


(read mode or write mode).
After importing pickle module we need to open the data file in binary mode. We

need to use alphabet “b” with file file opening mode to open a file in binary

mode

Example1:

f1=open("file1.txt","wb")

**Above statement will creater a new file file1.txt in binary mode. w for write

mode and b for binary mode.

Example2:

f2=open("file2.txt","ab")

**Above statement will open file named file2.txt in append as well as binary

mode. a for append mode and b for binary mode.

Example2:

f3=open("file2.txt","rb")
**Above statement will open file named file2.txt in read as well as binary mode.

r for read mode and b for binary mode.

3. Process binary file by writing\reading


objects.
We can use pickle.dump() method to write data into binary file and

pickle.load() method to read data from binary mode.

4. Close the file.


f1.close( )

You must first complete Working with binary files in Python before viewing this
Lesson

How to Write data into a Binary File in


Python | Writing data into a binary file
using Python
To write an object to a binary file opened in the write mode, we should use

dump( ) function of pickle module as per the following syntax :

pickle.dump(<object>, <file-handler>)

For example, if you have a file open in handle f1 as

f1=open(“file1.txt”,”wb”)

1. Python program to write a list namely


list1 in the file named file1.txt
import pickle

f1=open("file1.txt","wb")

list1=[1,'Lovejot','Teacher']

pickle.dump(list1,f1)

f1.close()

2. Python program to write a tuple


namely t1 in the file named file2.txt
import pickle

f2=open("file2.txt","wb")

t1=(2,'Sumit','XII']

pickle.dump(t1,f2)

f2.close()

3. Python program to write a dictionary


namely d1 in the file named file3.txt
import pickle

f3=open("file3.txt","wb")

d1={'Rollno':1, name:'Anil'}

pickle.dump(d1,f3)

f3.close()

4. Python program to create a binary file named


employee.dat and write details of employees available
in the form of dictionaries.
import pickle

# dictionary objects

E1={ ‘Empno’ :101, ‘Name’ : ‘Ramesh’ , ‘Salary’ : 17000}

E2={ ‘Empno’ :102, ‘Name’ : ’’ , ‘Age’ : 30, ‘Salary’ : 18000}

#open file in write mode

file1 = open (‘Employee.dat’ , ‘wb’)

#write to the file

pickle.dump (E1 ,file1)

pickle.dump (E2 , file1)

#close file

file1.close( )

5. Python program to create a binary


file named student.dat . Data of students
must be put at run time then it should be
stored in file. The structure of data is
(rollno, name, marks).
import pickle

s={ } #declare empty dictionary


file2 = open(‘student.dat’ , ‘wb’) #open file

R = int (input (“Enter roll number=“ ) )

N = input (“Enter name =“ )

M = float(input (“Enter marks =“ )

# add read data into dictionary

S [‘Rollno’] = R

S [‘Name’] = N

S[‘Marks’] = M

# now write into the file

pickle.dump (s ,file2)

file2.close( )

Appending Records in Binary File in


Python
Appending records in binary files is similar to writing record but there are two

differences:
i. We need to open binary file in append mode (“ab”).

ii. If file doesn’t exit, it will create a new file .

iii. If file already exits, it will write new record at the end of existing file.

# Python program to append a list


namely list1 in the file named file1.txt
import pickle

f1=open("file1.txt","ab")

list1=[2,'Ayush','Student']

pickle.dump(list1,f1)

f1.close()

#Python program to append a tuple


namely t1 in the file named file2.txt
import pickle

f2=open("file2.txt","ab")

t1=(3,'Sunita','XI']

pickle.dump(t1,f2)

f2.close()

#Python program to append a dictionary


namely d1 in the file named file3.txt
import pickle

f3=open("file3.txt","ab")

d1={'Rollno':2, name:'Sumit'}
pickle.dump(d1,f3)

f3.close()

#Python program to append student records to an


existing file student.dat by getting input from user.
import pickle

Students ={ } #empty dictionary created to store records

file1 = open ('Student.dat', 'ab')

choice = 'y'

while choice == 'y' :

#Read values of rollno, name and marks

R=int(input("Enter roll number of student = "))

N=input("Enter name =")

M=float (input("Enter marks = "))

#put values of variables R,N, M in dictionary

Students['Rollno'] =R

Students['Name'] =N

Students['Marks'] =M

pickle.dump (Students, file1) #Write record into the file


choice=input("Do you want to add more records (y/n))

file1.close( )

Output

Enter roll number of student = 101

Enter name =anita

Enter marks = 88

Do you want to add more records (y/n)…y

Enter roll number of student = 102

Enter name =sunil

Enter marks = 56

Do you want to add more records (y/n)n

How to Read data from a Binary


File in Python | Reading data from
binary file in Python
After writing data into binary file using dump() method of pickle module, we can

read and display content of binary file load( ) method of the pickle module.

Reading data from binary file is known as unpickling.

The syntax of load( ) method is


<object> =pickle.load(<filehandle>)

#Program to read and display data stored in binary file Employee.dat as

created in program 4 given in previous post.

import pickle

Emp = {} #Empty dictionary object to stored records read from Employee.data

Empfile = open('Employee.dat', 'rb') #open binary file in read mode

try:

while True : # It will become False upon EOF

Emp = pickle.load(F) #Read record in Emp dictionary from file handle


Empfile

print (Emp) # print the record

except EOFError :

Empfile.close()

Output

{ ‘Empno’ :101, ‘Name’ : ‘Ramesh’, ‘Age’ : 40, ‘Salary’ : 17000}

{ ‘Empno’ :102, ‘Name’ : ’Mohan’ , ‘Age’ : 30, ‘Salary’ : 18000}

#Program to create a binary file named


myfile.dat and store a string value in it.
import pickle

S =”This is string value”

with open(“myfile.dat”, “wb”) as f :

pickle.dump (S,f)
print(“file successfully created.”)

f.close()

Above program created a binary file namely myfile.dat that stored the string

variable S in binary format.

# Program to read data from the file


myfile.dat created in previous program
and display all the text before the letter
‘v’,
import pickle

S = ‘‘

with open (“myfile.dat”, “rb”)as f :

S = pickle.load(fh)

S1 =S.split(‘v’)

print(S1[0])

f.close()

Output

This is string

Searching record from a binary file in


Python
To search something in a file, we need to follow given steps:

1. Open the file in read mode.


2. Read the contents of file record by record
3. Look for the desired item in record.
4. If found, “Value is found”.
5. If not found, read the next record and look for the desired item.
6. If desired item is not found in any of the records, “No such item found“.

# Program to open file Employee.dat containing following records. Search

for records with Empno=101. If found, display the record.

{‘Empno’ :101, ‘Name’ : ‘Ramesh’, ‘Age’ : 40, ‘Salary’ : 17000}

{‘Empno’ :102, ‘Name’ : ’Mohan’ , ‘Age’ : 30, ‘Salary’ : 18000}

import pickle

emp ={ } # empty dictionary object to hold records

found = False

F = open(‘Employee.dat’, ‘rb’) # open binary file in read mode

try :

print (“Searching in file Employee.dat… “)

while True: # It will become False upon EOF(End of file) exception

emp=pickle.load(F) #read record in emp dictionary from file handle F

if emp[‘Empno’]==101:

print (emp) #print the record

found = True

except EOFError :

if found == False :

print (“No such records found in the file “)

else :
print(“Search successful.”)

F.close( ) #close file

Output

Searching in file stu.dat…

{‘Empno’ :101, ‘Name’ : ‘Ramesh’, ‘Age’ : 40, ‘Salary’ : 17000}

Search successful.

# Program to open file Employee.dat


containing following records. Search for
records with age>30. If found, display
the record.
{‘Empno’ :101, ‘Name’ : ‘Ramesh’, ‘Age’ : 40, ‘Salary’ : 17000}

{‘Empno’ :102, ‘Name’ : ’Mohan’ , ‘Age’ : 30, ‘Salary’ : 18000}

import pickle

emp ={} # empty dictionary object to hold records

found = False

F = open(‘Employee.dat’, ‘rb’) # open binary file in read mode

try :

print (“Searching in file Employee.dat… “)

while True: # It will become False upon EOF(End of file) exception

emp=pickle.load(F) #read record in emp dictionary from file handle F

if emp[‘Age’]>30:
print (emp) #print the record

found = True

except EOFError :

if found == False :

print (“No such records found in the file “)

else :

print(“Search successful.”)

F.close( ) #close file

Output

Searching in file stu.dat…

{‘Empno’ :101, ‘Name’ : ‘Ramesh’, ‘Age’ : 40, ‘Salary’ : 17000}

Search successful.

You might also like