Basic Python II
Basic Python II
Basic Python II
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
type.
1. Creating a List
To create a list, we can put multiple values within the pair of square
brackets.
Syntax:
list.
Examples:
[ 1,2,3,] List of integers
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]
>>> 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]
>>> list2=[1,2,[5,6,7],9]
>>> list2
[1, 2, [5, 6, 7], 9]
given below:
listname=list(<sequence>)
other list
Python Creates the individual elements of the list from the individual
elements of sequence.
Example 1:
>>> newlist1=list(‘Lovejot’)
>>> newlist1
[‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’]
Description
Example 2:
>>> t1=(1,3,5,7,9)
>>> newlist2=list(t1)
>>> newlist2
[1, 3, 5, 7, 9]
Description
[1,3,5,7,9]
Example 3:
>>> s1={2,4,6,8,10}
>>> newlist3=list(s1)
>>> newlist3
[2,4, 6,8,10]
Description
[2,4,6,8,10]
Example:
Reading list from keyboard
Description
Example
(Backward Indexing)
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.
Listname[First_index,Last_index,Gap].
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.
syntax of len() is
len(listname)
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.
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.
(+).
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
Example:
>>> list1=[11,22,33]
>>> list1*2
[11, 22, 33, 11, 22, 33] #Elements of list1 are repeated twice in the output.
If all elements are two lists are same, then two lists are considered
>>>> 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
parenthesis.
Syntax:
tuple.
Examples:
( 1,2,3)
Tuple of integers
(‘a’,’b’,’c’ )
Tuple of characters
( ‘a’,1,’b’,3.5 )
Tuple of mixed values
(‘First’,’Second’ )
Tuple of strings
Example 1
>>>t=(1)
>>>print(t)
Example 2
>>>t=3,
>>>print(t)
(3,)
Example 3
>>>t=(3,)
>>>print(t)
(3,)
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)
>>> tuple1
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150)
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)
>>> tuple2=(1,2,(5,6,7),9)
>>> tuple2
given below:
tuplename=tuple(<sequence>)
other tuple
Python Creates the individual elements of the tuple from the individual
elements of sequence.
Example 1:
>>> newtuple1=tuple('Lovejot')
>>> newtuple1
Description
Example 2:
>>> 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:
>>> s1={2,4,6,8,10}
>>> newtuple3=tuple(s1)
>>> newtuple3
(2,4, 6,8,10)
Description
(2,4,6,8,10)
keyboard.
Example 1:
Reading tuple from keyboard
>>> tuple3
Description
String India is entered from keyboard and it gets converted into tuple as (‘I’, ‘n’,
‘d’, ‘i’, ‘a’)
Example 2:
>>> tuple3
(1,3,4,5)
Description
Example
we have a tuple named tuple1=(10,30,40,50,60,99)
(Backward Indexing)
tuple1[-1].
Example
>>> classes=('xii','xi','x','ix')
>>> classes[0]
'xii'
>>> classes[2]
'x'
>>> classes[-1]
'ix'
>>> classes[-3]
'xi'
Example
>>> tuple1=[10,20,30,40,50,60,70)
>>> tuple1[0:3]
>>> tuple1[2:6]
>>> tuple1[-6:-3]
>>> tuple1[0:7:2]
(10, 30, 50, 70)
>>> tuple1[-7:-2:2]
>>> tuple1[::2]
#All tuple elements starting from index 0 onwards will be shown with a gap of 2
syntax of len() is
len(tuplename)
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.
Example:
>>> tuple1=(10,20,30,40,50,60,70)
>>> 10 in tuple1
True
>>> 25 in tuple1
False
#Output is False because 25 is not contained in the tuple.
True
False
operator (+).
Example:
>>> tuple1=(11,22,33)
>>> tuple2=(40,50,60)
>>> tuple1+tuple2
(11, 22, 33, 40, 50, 60)
>>> tuple1[0:2]+tuple2[1:3]
#Elements of tuple1 at indexes 0,1 and elements of tuple2 at indexes 1,2 are
joined together.
Example:
Example:
>>> tuple1=(11,22,33,44)
>>> tuple1*2
If all elements are two tuples are same, then two tuples are considered
Example:
>>> tuple1=(11,22,33)
>>> tuple2=(11,22,33)
>>> tuple3=(12,23,34)
>>> tuple4=(12,25)
>>> tuple5=(12,23,33)
>>> tuple1==tuple2
True
>>> tuple1<tuple2
False
>>> tuple1<tuple3
True
>>> tuple1>tuple3
False
>>> 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
<variable1>,<variable2>,<variable3>,…=tuplename
Example
We Have A Tuple as t1=(1,3,5,6)
a,b,c,d=t1
Example:
>>> t1=[1,3,5,6]
>>> a,b,c,d=t1
>>> print(a,b,c,d)
1356
Description
It can be deleted as
del t1
Example:
Python Code
>>> t1=[1,3,5,6]
>>del t1
>>> t1
t1
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
Syntax:
len(<tuple>)
Example:
>>> T1=(10,20,30,40)
>>> len(T1)
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
Syntax :
max(<tuple>)
value.
Example 1:
>>> T1=[10,20,30,40]
>>> max(T1)
40
>>> T2=['Sumit','Anil','Rahul']
>>> max(T2)
'Sumit'
Example 3:
>>> T3=['Sumit',10,'Anil',11,'Rahul',12]
>>> max(T3)
max(T3)
Example 4:
>>> max([3,4],(5,6))
max([3,4],(5,6))
TypeError: '>' not supported between instances of 'tuple' and 'tuple'
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
Syntax :
min(<tuple>)
value.
Example 1:
>>> T1=[10,20,30,40]
>>> min(T1)
10
Example 2:
>>> T2=['Sumit','Anil','Rahul']
>>> min(T2)
'Anil'
Example 3:
>>> T3=['Sumit',10,'Anil',11,'Rahul',12]
>>> min(T3)
min(T3)
Example 4:
>>> min([3,4],(5,6))
min([3,4],(5,6))
4. index()
This method is used to find first index position of value in a tuple. It
Syntax:
Tuple.index (<Val>)
Example 1:
>>> T1=[13,18,11,16,18,14]
>>> print(T1.index(18))
Example 2:
>>> print(T1.index(10))
T1.index(10)
exists in a tuple. If the given value is not in the tuple, it returns zero.
Syntax:
Tuple.count(<value>)
Example 1:
>>> T1=[13,18,11,16,18,14]
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>)
a tuple.
>>> t
()
>>>t=tuple([1,2,3])
>>>t
(1,2,3)
>>>t=tuple(“abc”)
>>>t
(‘a’,’b’,’c’)
>>> 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
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
2. Not a Sequence
is unordered collection.
3. Indexed by Keys, Not Numbers
Dictionaries are indexed by keys. A key can be any non mutable type.
non mutable.
>>> dict1
{0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}
Example:
>>> dict2
If there are duplicate keys, key appearing later will be taken in the
output.
5. Mutable
<dictionary>[<key>]=<value>
Example
>>> dict1={0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}
>>> dict1['str']="STRING"
>>> dict1
The key: value pairs in a dictionary are associated with one another
is called mapping.
1. Creating a Dictionary in Python
To create a dictionary, we need to put key:value pairs within curly
braces.
<dictionary-name>={<key>:<value>,<key>:<value>…}
Elements of dictionary has two parts namely key followed by colon (:)
Braces (curly brackets) specify the start and end of the dictionary.
There are four key: value pairs. Following table shows the key- value
“Lovejot”:”Computer
Lovejot Computer
science”
Example
>>> Teachers
etc.
>>> dict={[1]:"abc"}
dict={[1]:"abc"}
Example:
Employee ={‘name’:’john’,’salary’:10000,’age’:24}
Employee ={}
Employee=dict()
and values. There are multiple ways to provide keys and values to
dict() function.
function
assignment operator
Example:
>>> Employee
Example:
>>> Employee
Keys and values are enclosed separately in parentheses and are given
function.
Example
>>> Employee
Example 1:
>>> Employee
Example 2:
>>> Employee
Syntax
<dictionary-name>[<key>]
Computer Science
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']
vowels['Vowel6']
KeyError: 'Vowel6'
Above error means that we can’t access the value of a particular key
following syntax:
for<item>in<Dictionary>:
by one which we can use inside the body of the for loop.
Example:
Python Code
print (key,":",dict1[key])
Output
5 : number
a : string
True : Boolean
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
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”.
function.
Example:
>>> dict1.keys()
dictionary>.values() function.
Example
>>> dict1.values()
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
<dictionary>[<key>]=<value>
Example
>>> Employee['Dept']='Sales'
#Add new element with key=’Dept’, value=’Sales’
>>> Employee
as a key.
Dictionary>[<key>]=<value>
Example
>>> dict1={0: 'numeric key', 'str': 'string key', (4, 5): 'tuple key'}
>>> dict1['str']="STRING"
>>> dict1
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.
del<dictionary>[<key>]
Example:
>>> Employee
<dictionary>.pop(<key>)
Example
>>> Employee={'name': 'John', 'salary': 10000, 'age': 24}
>>> Employee.pop('name')
'John'
>>> Employee
The pop () method deletes the key: value pair for specified key but
If we try to delete key which does not exist, the Python returns error.
<dictionary>.pop(<key>,<Error-message>)
Example
'Not Found'
statement as
<key> in <dictionary>
* The in operator will return True if the given key is present in the
* The not in operator will return True if given key is not present in the
Example
True
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>)
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
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()
clear.
Example 1:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp.clear()
>>> emp
{}
dictionary name.
Example 2:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp
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
argument.
Syntax:
<dictionary>.get(key,[default])
want to get.
Example 1:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp.get('age')
30
Example 2:
# 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
<dictionary>.items()
Example 1:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> T1=emp.items()
>>> T1
print(i)
('name', 'Munish')
('age', 30)
('designation', 'Teacher')
Example 2:
write a loop having two variables to access key value pairs as.
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> T1=emp.items()
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
Syntax:
<dictionary>.keys()
Example :
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp.keys()
6. values ()
This method returns all values from the dictionary as a sequence (a
Syntax:
<dictionary>.values()
Example:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp.values()
7. update ()
This method merges key: value pairs from the new dictionary into the
Syntax
<dictionary>.updates(<other-dictionary>)
Example:
>>> emp={'name':'Munish','age':30,'designation':'Teacher'}
>>> emp1={'name':'Rohit','Salary':40000}
>>> emp.update(emp1)
>>> emp
When we call a function, all the statements written within the function
Syntax of a Function:
def Func_name(Arguments):
Local Variables
Statement_Block
return(Expression)
Block.
by the function.
def message():
print("Hello Python")
def shownumber(num):
print(num)
parenthesis.
If no arguments are required then there must be empty pair of
statement
message()
Output
Hello Python
shownumber(10)
Output
10
Complete Program
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
used built in functions are input(), id(), type(), int(), float(), bool(),
len()etc.
can perform a specific task. Once a user defined function has been
or another program.
A user defined function can also take values from other functions and
Calling function: The function which calls another function within its
made.
within the parenthesis written after the function name. This type of
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.
def sum():
c=a+b
print ("sum=",c)
Output
sum= 5
sum() which reads values of two variables, adds them and shows their
Features:
def sum(a,b):
c=a+b
print ("sum=",c)
sum(10,5)
Output
sum= 15
function.
Features:
def sum(a,b ):
c=a+b
return(c)
s=sum(3,5)
Output
sum of 3 and 5 is 8
sum of 5 and 6 is 11
Features :
def sum():
c=a+b
return(c)
s=sum()
print("Sum=",s)
print("Sum=",sum())
Output
Sum= 5
Sum= 9
sum() It performs addition two values after reading them and result is
variables a and b are input and their sum is stored in variable c which
function. Values of variables a and b are input again and their sum is
You must first complete Python Functions Tutorial | Using Functions in Python 3
before viewing this Lesson
key=value pair.
their positions.
In the following program, formal parameter a gets 25 and formal
def show(a,b):
print(a,b)
show(25,10)
Output
25 10
parameter.
def show(var1):
print(var1)
show('Amit')
”’ Amit’ will be stored in formal parameter var1 and shown within function
body.”
Output
Amit
simply need to specify the name of list both as actual as well as formal
def show(list1):
print(list1)
L1=[10,20,30,40]
show(L1)
Output
def show(list1):
list1[0]='a'
L1=[10,20,30,40]
show(L1)
print(L1)
Output
element of list i..e changes made to list1 are reflected back to list L1.
argument.
Example – Program of function with tuple as parameter.
def show(tuple1):
print(list1)
T1=[10,20,30,40]
show(T1)
Output
def show(dict1):
print(list1)D1={1:’a’,2:’b’,3:’c’}
print(D1)
Output
The main use of default parameters is that we may or may not provide
value for default parameter while calling the function because function
function.
def show(a=5,b=10):
print(a,b)
Output
5 10
25 10
25 40
def display(fname,lname="Kumar"):
print(fname,lname)
display("amit") #fname gets 'amit', lname gets 'Kumar'
Output
amit Kumar
amit singh
are assigned to formal parameters on one to one basis i.e. First actual
def show(name,salary):
print(name,salary)
show('Amit',50000)
Output
Amit 50000
order we want.
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,
Output
name= Amit
age= 30
salary= 50000
Here var1 takes very first parameter value. All parameter values
tuples.
def show(var1,*var2):
print(num1)
print(var2)
show('Amit',1,3,4,5,6)
tuple in var2.
Output
Amit
(1, 3, 4, 5, 6)
following things:
(i) Docstring
Docstring is text written within the pair of triple quotes. it is basically
(iii) Class
We can also create more than class inside a Python module. Class may
(iv) Object
Object is anything having properties and behaviour. But in Python,
(v) Statements
We can write all valid statements of Python within a module.
(vi) Functions
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
Example
Module1.py
'''
'''
def sum(a,b):
return(a+b)
def subtract(a,b):
return(a-b)
created.
>>> help(Module1)
NAME
Module1
FILE
c:\python30\Module1.py
DESCRIPTION
FUNCTIONS
subtract(a, b)
sum(a, b)
>>>import Module1
>>> dir(Module1)
Example1:
Example2 :
Example3:
To import predefined modules math and random in a Python program
After importing a module, you can use any function or other element
<module-name>.<function-name>()
Example1:
Example2:
you can use from <module> import statement as per following syntax:
from<module>import<objectname>[,<objectname>[…]|*
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:
value of pi.
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,
To import all the items from a module we don’t have to prefix the
from<modulename>import *
Now, we can use all the functions, variables etc from math module,
import Module1
print(Module1.sum(10,5))
print(Module1.subtract(10,5))
Output
15
Example 2
import math
print(math.sqrt(9))
print(math.pow(2,3))
Output
3.0
8.0
Example 3
print(pow(2,3))
Output
3.0
8.0
Example 4
print(pow(2,3))
Output
3.0
8.0
take place:
name>.
functions.
functions of Python.
import math
Following table lists some useful math functions:
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
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
>> 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
3.9068905956085187
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
import math
s=(a+b+c)/2
Output
import math
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
randomly.
import random
i. random()
It returns a random floating point number in the between 0.0 and 1.0
(0.0, 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
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))
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))
Example 2:
>>> import random
>>> print(random.randrange(2,6))
Example 3:
>>> import random
functions.
mean()
mode()
median()
i. mean()
dictionary.
>>>import statistics
>>>list1=[1,3,4,5,4]
>>>print(statistics.mean(list1))
3.4
>>> t1=(1,3,4,5,4)
>>> print(statistics.mean(t1))
3.4
>>>d1={1:'a',3:'b',5:'c'}
>>>print(statistics.mean(d1))
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))
>>>t1=(1,3,4,5,4)
>>>print(statistics.mean(t1))
iii. median()
This function is used to find median value from a sequence of values.
returned.
>>>import statistics
>>>list1=[1,3,4,5,4]
>>>print(statistics.median(list1))
>>>t1=(1,3,4,5)
>>>print(statistics.mean(t1))
3.5
3.5
>>>d1={1:'a',3:'b',5:'c'}
>>>print(statistics.mean(d1))
Syntax:
<file_object> = open(<filename>)
OR
<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
<mode> is the file opening mode used to specify the operation we want to
perform on file.
Read only
[File must exist otherwise I/O error is
‘r’
generated ]
Append
Read only
file1 = open(“data.txt”)
OR
Example 2
OR
** We can also use single slash in the path but that may generate error
Example 3
OR
** We can also use single slash in the path but that may generate error
functions of Python. different functions to read and write data in Python are:
write()
read()
readline()
<file_object>.close();
Example:
file1.close()
file are:
There are two predefined functions provided by Python to write data
1. write()
write() function is used to write content into a data file.The syntax of
<fileobject>.write(str)
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”
Example 2
file2=open("data1.txt","w")
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
Example 3
file3=open("data3.txt","w")
for i in range(3):
name=input('Enter name')
file3.write(name + '\n' )
file3.close()
Output
Enter namesuman
Enter nameraman
#Above code will create a new file data3.txt and write following three
2. writelines()
writelines() function is also used to write content into a data file.The
<fileobject>.writelines(List)
List refers to a List whose values we want to write into data file.
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
Example 2
file6=open("data6.txt","w")
L1=[]
for i in range(3):
name=input('Enter name')
L1.append(name+"\n")
file6.writelines(L1)
file6.close()
Output
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.
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+” .
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
Syntax 2:
<file_object>.read(N)
Here file_object is the name of file handler object that is linked to a data file.
Example:
s=file1.read(6)
print(s)
Output
I am a
** Above code will display first six characters (including spaces) from data file data.txt
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:
file1 = open(“data1.txt”)
s=file1.readline()
print(s)
Output
** 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
** Above code will display complete data from file one line at a time from file data1.txt
Syntax:
<file_object>.readlines()
Here file_object is the name of file handler object that is linked to a data file.
Example:
Example 1:
Program to demonstrate the use of
readlines() method in Python.
file1 = open(“data1.txt”)
s=file1.readlines()
print(s)
Output
** 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()
file1.close( )
Output
Number of lines=3
By using flush( ) function we can force Python to write the contents of buffer to
f.flush( )
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")
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
while s :
print(s)
Fileinput.close ( )
Output
101,aman
s=" "
while s :
s = Fileinput.readline( ) #Read a line from file
print(w)
Fileinput.close ( )
Output
This
is
data
file
It
contains
data
about
student
Name
of
student
is
Amit
s=" "
count=0
while s :
count+=1
print("Number of words=",count)
Fileinput.close ()
Output
Number of words= 16
s=" "
count=0
while s :
print("Number of characters=",count)
Fileinput.close ()
Output
Number of characters= 78
s=" "
count=0
count1=0
while s :
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
Fileout.write(rec)
Fileout.close( )
Output
>>>
Name : Amit
Marks : 74.6
Rollno : 18
Name : John
Marks : 99.2
while str :
str = fileinp.readline( )
print(str)
Fileinp.close ( )
Output
>>>
17,Amit , 74.6
work with the pickle module, we need to import it in our program using import
We can use dump( ) and load ( ) methods of pickle module to write and read
module as:
import pickle
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
Example2:
f2=open("file2.txt","ab")
**Above statement will open file named file2.txt in append as well as binary
Example2:
f3=open("file2.txt","rb")
**Above statement will open file named file2.txt in read as well as binary mode.
You must first complete Working with binary files in Python before viewing this
Lesson
pickle.dump(<object>, <file-handler>)
f1=open(“file1.txt”,”wb”)
f1=open("file1.txt","wb")
list1=[1,'Lovejot','Teacher']
pickle.dump(list1,f1)
f1.close()
f2=open("file2.txt","wb")
t1=(2,'Sumit','XII']
pickle.dump(t1,f2)
f2.close()
f3=open("file3.txt","wb")
d1={'Rollno':1, name:'Anil'}
pickle.dump(d1,f3)
f3.close()
# dictionary objects
#close file
file1.close( )
S [‘Rollno’] = R
S [‘Name’] = N
S[‘Marks’] = M
pickle.dump (s ,file2)
file2.close( )
differences:
i. We need to open binary file in append mode (“ab”).
iii. If file already exits, it will write new record at the end of existing file.
f1=open("file1.txt","ab")
list1=[2,'Ayush','Student']
pickle.dump(list1,f1)
f1.close()
f2=open("file2.txt","ab")
t1=(3,'Sunita','XI']
pickle.dump(t1,f2)
f2.close()
f3=open("file3.txt","ab")
d1={'Rollno':2, name:'Sumit'}
pickle.dump(d1,f3)
f3.close()
choice = 'y'
Students['Rollno'] =R
Students['Name'] =N
Students['Marks'] =M
file1.close( )
Output
Enter marks = 88
Enter marks = 56
read and display content of binary file load( ) method of the pickle module.
import pickle
try:
except EOFError :
Empfile.close()
Output
pickle.dump (S,f)
print(“file successfully created.”)
f.close()
Above program created a binary file namely myfile.dat that stored the string
S = ‘‘
S = pickle.load(fh)
S1 =S.split(‘v’)
print(S1[0])
f.close()
Output
This is string
import pickle
found = False
try :
if emp[‘Empno’]==101:
found = True
except EOFError :
if found == False :
else :
print(“Search successful.”)
Output
Search successful.
import pickle
found = False
try :
if emp[‘Age’]>30:
print (emp) #print the record
found = True
except EOFError :
if found == False :
else :
print(“Search successful.”)
Output
Search successful.