Python Lab Manual r22
Python Lab Manual r22
output:
('x=', 20)
('x is Type of', <type 'int'>)
('y=', 20.5)
('y is Type of', <type 'float'>)
('z=', (5+1j))
('z is Type of', <type 'complex'>)
2. write a program to perform different arithmetic operations on numbers in python
program:
Output:
>>>
Enter a value7
Enter b value9
('Addition of a and b is ', 16)
('Subtraction of a and b ', -2)
('Multiplication of a and b ', 63)
('Division of a and b ', 0)
('Remainder of a and b ', 7)
('Exponent of a and b ', 40353607)
('Floor division of a and b ', 0)
3. Write a program to create, concatenate and print a string and accessing sub-string from a
given string
program:
output:
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime));
'''
%a : Abbreviated weekday name.
%b : Abbreviated month name.
%d : Day of the month as a decimal number [01,31].
%H : Hour (24-hour clock) as a decimal number [00,23].
%M : Minute as a decimal number [00,59].
%S : Second as a decimal number [00,61].
%Z : Time zone name (no characters if no time zone exists).
%Y : Year with century as a decimal number.'''
Output:
program:
output:
Enter first number: 10
Enter second number: 90
Enter third number: 56
('The largest number is', 90)
program:
output:
Pattern 1:
Program:
n=5
for i in range(1,n+1):
print(" ",end=’ ‘)
print("*",end=’ ‘),
print()
output:
***
*****
*******
*********
Pattern 2:
Program:
n=5
for i in range(1,n+1):
print(" ",end='')
print(i,end='')
print()
output:
222
33333
4444444
555555555
Pattern 3:
Program:
n=5
for i in range(1,n+1):
print(" ",end='')
print("*",end=' ')
print()
output:
**
***
****
*****
Pattern 4:
Program:
n=5
for i in range(1,n+1):
print(" "),
print(i),
print()
output:
22
333
4444
55555
Pattern 5:
Program:
n=5
for i in range(n,0,-1):
print(" "),
print("*"),
print()
output:
*********
*******
*****
***
*
Pattern 6:
Program:
n=5
for i in range(n,0,-1):
print(" "),
print(n-i+1),
print()
output:
111111111
2222222
33333
444
5
Pattern 7:
Program:
n=5
print(column),
print()
output:
12
123
1234
12345
Pattern 8:
Program:
n=5
print(rows),
print()
output:
22
333
4444
55555
Pattern 9:
Program:
n=5
print(rows),
print()
output:
11111
2222
333
44
5
Pattern 10:
Program:
n=5
print(columns),
print()
output:
1 2 3 4 5 ()
1 2 3 4 ()
1 2 3 ()
1 2 ()
1 ()
8. Write a Python script that prints prime numbers less than 20
program:
ulmt=20;
fornum in range(ulmt):
ifnum> 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Output:
11
13
17
19
program:
snakes=['python','anaconda','fish','cobra','mamba']
animals=pets+snakes
snakes.remove("fish")
Output:
('Animals are :', ['cat', 'dog', 'rat', 'pig', 'tiger', 'python', 'anaconda', 'fish', 'cobra', 'mamba'])
program:
def union(list1,list2):
final_list=list1+list2
return final_list
list1=[23,15,2,14,13,16,20,52]
list2=[2,48,15,12,26,32,47,54]
Output:
('union of two lsts', [23, 15, 2, 14, 13, 16, 20, 52, 2, 48, 15, 12, 26, 32, 47, 54])
11.python program to find the intersection of two lists.
program:
list1=[1,2,3,4,5,6]
print(list1)
list2=[2,4,6,8,10,12]
print(list2)
newlist=[]
if ele in list1:
newlist.append(ele)
print("intersection is",newlist)
Output:
>>>
[1, 2, 3, 4, 5, 6]
program:
for x in T:
print(x)
if "apple" in T:
Output:
('\n Created tuple is :', ('apple', 'banana', 'cherry', 'mango', 'grape', 'orange'))
apple
banana
cherry
mango
grape
orange
Yes, 'apple' is in the fruits tuple
13. Python program to remove the “i” th occurrence of the given word in a list where words
repeat
program:
def removeithword(list1,word,N):
newlist=[]
count=0
for i in list1:
if(i==word):
count=count+1
if(count!=N):
newlist.append(i)
else:
newlist.append(i)
list1=newlist
if count==0:
else:
return newlist
list2=['hi','helo','hi','welcome']
word='hi'
n=2
removeithword(list2,word,n)
Output:
14. Python program to count the occurrences of each word in a given string sentence
program:
string=raw_input("enter string")
counts = dict()
words = string.split()
if word in counts:
counts[word] += 1
else:
counts[word] = 1
output:
('count of occurance of each word in a given string is:', {'use': 1, 'python': 2, 'is': 1, 'welcome': 1,
'lab': 1, 'to': 2, 'hi': 1, 'easy': 1, 'hello': 1})
15. Python program to check if a substring is present in a given string
program:
substring="python"
s=string.split()
if substring in s:
print("yes,it is present")
else:
print("not present")
Output:
yes, it is present
16. Write a program to demonstrate working with dictionaries in python.
program:
for x in dict1:
print(x)
for x in dict1:
print(dict1[x])
#Adding items
dict1["Phno"]=85457854
#Updateddictoinary
#Change values
dict1["StuName"]="Madhu"
#Updateddictoinary
dict1.pop("StuAge");
#Updateddictoinary
#Length of Dictionary
#Copy a Dictionary
dict2=dict1.copy()
#Newdictoinary
dict1.clear()
Output:
('\n Dictionary is :', {'StuName': 'Naveen', 'StuCity': 'Hyderabad', 'StuAge': 21, 'StdNo': '532'})
StuName
StuCity
StuAge
StdNo
Naveen
Hyderabad
21
532
('\n Uadated Dictionary is :', {'StuName': 'Naveen', 'Phno': 85457854, 'StuCity': 'Hyderabad',
'StuAge': 21, 'StdNo': '532'})
('\n Uadated Dictionary is :', {'StuName': 'Madhu', 'Phno': 85457854, 'StuCity': 'Hyderabad',
'StuAge': 21, 'StdNo': '532'})
('\n Uadated Dictionary is :', {'StuName': 'Madhu', 'Phno': 85457854, 'StuCity': 'Hyderabad',
'StdNo': '532'})
('\n New Dictionary is :', {'StuName': 'Madhu', 'Phno': 85457854, 'StuCity': 'Hyderabad', 'StdNo':
'532'})
program:
l1=[1,2,3]
l2=[‘a’,’b’,’c’]
dictionary=dict(zip(l1,l2))
print(dictionary)
output:
18. Python program to count the frequency of words appearing in a string using a dictionary
def wordcount(str):
counts=dict()
words=str.split()
if word in counts:
counts[word]=counts[word]+1
else:
counts[word]=1
return counts
string=raw_input("enter string")
print(wordcount(string))
output:
enter stringhai hello welcome hai how r u
19. Python program to create a dictionary with key as first character and value as
program:
words = string.split()
dictionary = {}
dictionary[word[0]] = []
dictionary[word[0]].append(word)
else:
dictionary[word[0]].append(word)
print(dictionary)
Output:
>>>
{'a': ['and'], 'e': ['easy'], 'i': ['it', 'is'], 'l': ['lab', 'learn'], 'p': ['python'], 't': ['to'], 'w': ['welcome'], 'v':
['very']}
20. Python program to find the length of a list using recursion
program:
len=0
def length_list(list1):
global len
if list1:
len=len+1
length_list(list1[1:])
return len
list1=[1,23,45,6,7]
len=length_list(list1)
Output:
program:
defrecur_fact(n):
if n == 1:
return n
else:
return n*recur_fact(n-1)
ifnum< 0:
elifnum == 0:
else:
output:
Enter a number: 6
program:
importfibonacci
fibonacci.fib(num)
Fibonacci.py
a, b = 0, 1
while b < n:
print(b)
a, b = b, a+b
Output:
5
23.Write a python program to define a module and import a specific function in that module to
another program
program:
arth.py
def Add(a,b):
c=a+b
return c
def Sub(a,b):
c=a-b
return c
prg24.py:
print("Addition is : ",Add(num1,num2))
print("Subtraction is : ",Sub(num1,num2))
Output:
24. Python program to read a file and capitalize the first letter of every word in the file.
program:
program:
fname = open('file1.txt','r')
for line in fname:
l=line.title()
print(l)
output:
>>>
Hai
Hello
program:
file1.txt:
hai
hello
welcome to python lab
Program:
file1=raw_input("enter file1")
file2=raw_input("enter file2")
f1=open(file1,'r')
f2=open(file2,'w')
cont=f1.readlines()
for i in range(0,len(cont)):
f2.write(cont[i])
f2.close()
print("contents of first file copied to second")
f2=open(file2,'r')
cont1=f2.read()
print("content of second file is:")
print(cont1)
f1.close()
f2.close()
Output:
>>>
enter file1file1.txt
enter file2file2.txt
contents of first file copied to second
content of second file is:
hai
hello
welcome to python lab
26. Write a Python class to implement pow(x, n)
program:
def power(x,n):
if(n==0):
return 1
if(x==0):
return 0
return x*power(x,n-1)
x=int(input("enter x value"))
n=int(input("enter n value"))
Output:
>>>
enter x value4
enter n value3
program:
file1.txt:
hai
hello
welcome to python lab
f=open('file1.txt','r')
rev=f.read()
revdata=rev[::-1]
print("Reversed data is:",revdata)
Output:
>>>
('Reversed data is:', 'bal nohtyp ot emoclew\nolleh\niah')
28. Write a program that inputs a text file. The program should print all of the unique words
in the file in alphabetical order
program:
file.txt:
This is python program
welcome to python
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
words=[];
for line in fh:
words += line.split()
words.sort()
Output:
def even(n):
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
def armstrong(n):
t=n
sum1=0
while n>0:
d=n%10
sum1=sum1+d*d*d;
n=n//10
if t==sum1:
print("armstrong")
else:
print("not armstrong")
def reverse(n):
rev=0
while n>0:
d=n%10
rev=rev*10+d
n=n//10
return rev
n=int(input("enter number"))
even(n)
armstrong(n)
print("reverse number is:",reverse(n))
Output:
enter number153
(153, 'is odd')
armstrong
('reverse number is:', 351)
30. Python program to demonstrate modules and packages
program:
First of all, we need a directory. The name of this directory will be the name of the
package, which we want to create. We will call our package "mypack". This directory
needs to contain a file with the name __init__.py. This file can be empty,
mypack
__init__.py Module2.py
Module1.py
module1.py
def message():
print("welcome to python lab")
print("python is easy to use and easy to learn")
module2.py
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a//b
prg30.py
from mypack import module1,module2
module1.message()
res=module2.sum(3,4)
print("sum is=",res)
res=module2.sub(38,4)
print("sum is=",res)
res=module2.mul(36,4)
print("sum is=",res)
res=module2.div(10,4)
print("sum is=",res)
Output:
class display:
def __init__(self):
self.string=" "
def get(self):
self.string=raw_input("enter string")
def put(self):
print("string is:",self.string)
obj1=display()
obj1.get()
obj1.put()
output:
>>>
enter stringhai hello
('string is:', 'hai hello')
32. Write a Python class to reverse a string word by word.
program:
class reverse:
def revword(self,str):
sp=str.split()
sp.reverse()
res=" ".join(sp)
return res
string=raw_input("enter string")
print("reverse of string is:",reverse().revword(string))
output: