0% found this document useful (0 votes)
8 views45 pages

Python Lab Manual r22

The document is a Python Lab Manual for the Department of Computer Science and Engineering at Acharya Nagarjuna University. It contains a list of experiments and programming tasks designed to teach various Python programming concepts, including data types, arithmetic operations, string manipulation, file handling, and object-oriented programming. Each task includes sample programs and expected outputs to guide students in their learning.

Uploaded by

shankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Python Lab Manual r22

The document is a Python Lab Manual for the Department of Computer Science and Engineering at Acharya Nagarjuna University. It contains a list of experiments and programming tasks designed to teach various Python programming concepts, including data types, arithmetic operations, string manipulation, file handling, and object-oriented programming. Each task includes sample programs and expected outputs to guide students in their learning.

Uploaded by

shankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

University College of Engineering & Technology

ACHARYA NAGARJUNA UNIVERSITY


PYTHON LAB MANUAL
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

SUBJECT NAME : Python Programming Lab

SUBJECT CODE : AI & ML/CE/CSE/CS/DS/ECE/EEE/ME 162 (R22)

YEAR : I/IV B.TECH II Semester


AI & ML/CE/CSE/CS/DS/ECE/EEE/ME 162 (R22)
Python Programming Lab
List of Experiments

1. Write a program to demonstrate different number datatypes in python.


2. Write a program to perform different arithmetic operations on numbers in python
3. Write a program to create, concatenate and print a string and accessing substring from a given
string
4. Write a python script to print the current date in following format "Sun May 29 02:26:23
IST 2017"
5. Write a python program to find largest of three numbers
6. Write a python program to convert temperature to and from Celsius to Fahrenheit
7. Write a python program to construct the following patterns using nested for loop:

8. Write a python program to print prim numbers less than 20


9. Write a python program to create, append and remove lists in python
10. Python program to find the union of two lists.
11. Python program to find the intersection of two lists.
12. Write a program to demonstrate working with tuples in python
13. Python program to remove the "i" th occurrence of the given word in a list where words
repeat
14. Python program to count the occurrences of each word in a given string sentence.
15. Python program to check if a substring is present in a given string.
16. Write a program to demonstrate working with dictionaries in python
17. Python program to map two lists into a dictionary.
18. Python program to count the frequency of words appearing in a string using a dictionary.
19. Python program to create a dictionary with key as first character and value as words
starting With that character.
20. Python program to find the length of a list using recursion.
21. Write a python program to find factorial of a number using recursion
22. Write a python program to define a module to find Fibonacci Numbers and import
the module to another program
23. Write a python program to define a module and import a specific function in that module to
another program
24. Python program to read a file and capitalize the first letter of every word in the file.
25. Write a script named copyfile.py. This script should prompt the user for the names of two
text files. The contents of the first the second file
26. Write a Python class to implement pow(x,n)
27. Python program to read the contents of a file in reverse order.
28. Write a program that inputs a text file. The program should print all of the unique words in
the file in alphabetical order
29. Python programs to demonstrate functions
30. Python program to demonstrate modules and packages
31. Python program to create a class in which one method accepts a string from the user and another prints
it.
32. Write a Python class to reverse a string word by word.
1. write a program to demonstrate different number datatypes in python
program:
x = 20
print("x=",x)
print("x is Type of",type(x));
y = 20.5 #float
print("y=",y)
print("y is Type of",type(y));
z = 5+1j#complex
print("z=",z)
print("z is Type of",type(z));

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:

a=int(input("Enter a value")); #input() takes data from console at runtime as string.


b=int(input("Enter b value")); #typecast the input string to int.
print("Addition of a and b is ",a+b);
print("Subtraction of a and b ",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b ",a/b);
print("Remainder of a and b ",a%b);
print("Exponent of a and b ",a**b); #exponent operator (a^b)
print("Floor division of a and b ",a//b); # floar division

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:

s1=input("Enter first String : ");


s2=input("Enter second String : ");
print("First string is : ",s1);
print("Second string is : ",s2);
print("concatenations of two strings :",s1+s2);
print("Substring of given string :",s1[1:4]);

output:

Enter first String : hello


Enter second String :manasa
('First string is : ', 'hello')
('Second string is : ', 'manasa')
('concatenations of two strings :', 'hellomanasa')
('Substring of given string :', 'ell')
4. Write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017”
program:

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:

Sat Apr 15 12:01:35 India Standard Time 2023

5. Write a python program to find largest of three numbers

program:

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)

output:
Enter first number: 10
Enter second number: 90
Enter third number: 56
('The largest number is', 90)

6. Write a Python program to convert temperatures to and from Celsius, Fahrenheit.

program:

print("Convert temperatures from Celsius to Fahrenheit \n")


cel = float(input("Enter Temperature in Celsius: "))
fahr = (cel*9/5)+32
print("Temperature in Fahrenheit =",fahr)

print("Convert temperatures from Fahrenheit to Celsius \n")


fahr = float(input("Enter Temperature in Fahrenheit: "))
cel=(fahr-32)*5/9;
print("Temperature in Celsius =",cel)

output:

Convert temperatures from Celsius to Fahrenheit

Enter Temperature in Celsius: 36


('Temperature in Fahrenheit =', 96.8)
Convert temperatures from Fahrenheit to Celsius

Enter Temperature in Fahrenheit: 98.3


('Temperature in Celsius =', 36.833333333333336)
7. Write a python program to construct the following patterns using nested for loop:

Pattern 1:

Program:

n=5

for i in range(1,n+1):

for spaces in range(n-i):

print(" ",end=’ ‘)

for star in range(2*i-1):

print("*",end=’ ‘),

print()

output:

***

*****

*******

*********
Pattern 2:

Program:

n=5

for i in range(1,n+1):

for spaces in range(n-i):

print(" ",end='')

for num in range(2*i-1):

print(i,end='')

print()

output:

222

33333

4444444

555555555
Pattern 3:

Program:

n=5

for i in range(1,n+1):

for spaces in range(n-i):

print(" ",end='')

for star in range(i):

print("*",end=' ')

print()

output:

**

***

****

*****
Pattern 4:

Program:

n=5

for i in range(1,n+1):

for spaces in range(n-i):

print(" "),

for number in range(i):

print(i),

print()

output:

22

333

4444

55555
Pattern 5:

Program:

n=5

for i in range(n,0,-1):

for spaces in range(n-i):

print(" "),

for star in range(2*i-1):

print("*"),

print()

output:

*********

*******

*****

***

*
Pattern 6:

Program:

n=5

for i in range(n,0,-1):

for spaces in range(n-i):

print(" "),

for row in range(2*i-1):

print(n-i+1),

print()

output:

111111111

2222222

33333

444

5
Pattern 7:

Program:

n=5

for rows in range(1,n+1):

for column in range(1,rows+1):

print(column),

print()

output:

12

123

1234

12345
Pattern 8:

Program:

n=5

for rows in range(1,n+1):

for columns in range(1,rows+1):

print(rows),

print()

output:

22

333

4444

55555
Pattern 9:

Program:

n=5

for rows in range(1,n+1):

for columns in range(n+1-rows):

print(rows),

print()

output:

11111

2222

333

44

5
Pattern 10:

Program:

n=5

for rows in range(1,n+1):

for columns in range(1,n+2-rows):

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:

print("Prime numbers between 1 and 20 are:")

ulmt=20;

fornum in range(ulmt):

# prime numbers are greater than 1

ifnum> 1:

for i in range(2,num):

if (num % i) == 0:

break

else:

print(num)

Output:

Prime numbers between 1 and 20 are:

11

13

17
19

9. Write a program to create, append, and remove lists in python

program:

pets = ['cat', 'dog', 'rat', 'pig', 'tiger']

snakes=['python','anaconda','fish','cobra','mamba']

print("Pets are :",pets)

print("Snakes are :",snakes)

animals=pets+snakes

print("Animals are :",animals)

snakes.remove("fish")

print("updated Snakes are :",snakes)

Output:

('Pets are :', ['cat', 'dog', 'rat', 'pig', 'tiger'])

('Snakes are :', ['python', 'anaconda', 'fish', 'cobra', 'mamba'])

('Animals are :', ['cat', 'dog', 'rat', 'pig', 'tiger', 'python', 'anaconda', 'fish', 'cobra', 'mamba'])

('updated Snakes are :', ['python', 'anaconda', 'cobra', 'mamba'])


10. Python program to find the union of two lists.

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]

print("union of two lsts",union(list1,list2))

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=[]

for ele in list2:

if ele in list1:

newlist.append(ele)

print("intersection is",newlist)

Output:

>>>

[1, 2, 3, 4, 5, 6]

[2, 4, 6, 8, 10, 12]

('intersection is', [2, 4, 6])


12. Write a program to demonstrate working with tuples in python

program:

T = ("apple", "banana", "cherry","mango","grape","orange")

print("\n Created tuple is :",T)

print("\n Second fruit is :",T[1])

print("\n From 3-6 fruits are :",T[3:6])

print("\n List of all items in Tuple :")

for x in T:

print(x)

if "apple" in T:

print("\n Yes, 'apple' is in the fruits tuple")

print("\n Length of Tuple is :",len(T))

Output:

('\n Created tuple is :', ('apple', 'banana', 'cherry', 'mango', 'grape', 'orange'))

('\n Second fruit is :', 'banana')

('\n From 3-6 fruits are :', ('mango', 'grape', 'orange'))

List of all items in Tuple :

apple

banana

cherry

mango

grape

orange
Yes, 'apple' is in the fruits tuple

('\n Length of Tuple is :', 6)

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:

print("item not found")

else:

print("new list is:",list1)

return newlist

list2=['hi','helo','hi','welcome']

word='hi'

n=2

removeithword(list2,word,n)
Output:

('new list is:', ['hi', 'hi'])

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()

for word in words:

if word in counts:

counts[word] += 1

else:

counts[word] = 1

print("count of occurance of each word in a given string is:",counts)

output:

enter stringhi hello welcome to python lab python is easy to use

('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:

string="python progrmming lab"

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:

dict1 = {'StdNo':'532','StuName': 'Naveen', 'StuAge': 21, 'StuCity': 'Hyderabad'}

print("\n Dictionary is :",dict1)

#Accessing specific values

print("\n Student Name is :",dict1['StuName'])

print("\n Student City is :",dict1['StuCity'])

#Display all Keys

print("\n All Keys in Dictionary ")

for x in dict1:

print(x)

#Display all values

print("\n All Values in Dictionary ")

for x in dict1:

print(dict1[x])

#Adding items

dict1["Phno"]=85457854

#Updateddictoinary

print("\n Uadated Dictionary is :",dict1)

#Change values

dict1["StuName"]="Madhu"

#Updateddictoinary

print("\n Uadated Dictionary is :",dict1)


#Removing Items

dict1.pop("StuAge");

#Updateddictoinary

print("\n Uadated Dictionary is :",dict1)

#Length of Dictionary

print("Length of Dictionary is :",len(dict1))

#Copy a Dictionary

dict2=dict1.copy()

#Newdictoinary

print("\n New Dictionary is :",dict2)

#empties the dictionary

dict1.clear()

print("\n Uadated Dictionary is :",dict1)

Output:

('\n Dictionary is :', {'StuName': 'Naveen', 'StuCity': 'Hyderabad', 'StuAge': 21, 'StdNo': '532'})

('\n Student Name is :', 'Naveen')

('\n Student City is :', 'Hyderabad')

All Keys in Dictionary

StuName

StuCity

StuAge

StdNo

All Values in Dictionary

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'})

('Length of Dictionary is :', 4)

('\n New Dictionary is :', {'StuName': 'Madhu', 'Phno': 85457854, 'StuCity': 'Hyderabad', 'StdNo':
'532'})

('\n Uadated Dictionary is :', {})


17. Python program to map two lists into a dictionary

program:

l1=[1,2,3]

l2=[‘a’,’b’,’c’]

dictionary=dict(zip(l1,l2))

print(dictionary)

output:

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

18. Python program to count the frequency of words appearing in a string using a dictionary

def wordcount(str):

counts=dict()

words=str.split()

for word in words:

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

{'hai': 2, 'welcome': 1, 'how': 1, 'r': 1, 'u': 1, 'hello': 1}

19. Python program to create a dictionary with key as first character and value as

program:

words starting With that character

string="welcome to python lab and it is very easy to learn"

words = string.split()

dictionary = {}

for word in words:

if (word[0] not in dictionary.keys()):

dictionary[word[0]] = []

dictionary[word[0]].append(word)

else:

if (word not in dictionary[word[0]]):

dictionary[word[0]].append(word)

# Printing the dictionary

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)

print("length of list is:",len)

Output:

('length of list is:', 5)


21.Write a python program to find factorial of a number using Recursion.

program:

defrecur_fact(n):

if n == 1:

return n

else:

return n*recur_fact(n-1)

num = int(input("Enter a number: "))

# check is the number is negative

ifnum< 0:

print("Sorry, factorial does not exist for negative numbers")

elifnum == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of",num,"is",recur_fact(num))

output:

Enter a number: 6

('The factorial of', 6, 'is', 720)


22. Write a python program to define a module to find Fibonacci Numbers and import the
module to another program

program:

#import fibonacci module

importfibonacci

num=int(input("Enter any number to print Fibonacci series "))

fibonacci.fib(num)

Fibonacci.py

def fib(n): # write Fibonacci series up to n

a, b = 0, 1

while b < n:

print(b)

a, b = b, a+b

Output:

Enter any number to print Fibonacci series 7

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:

from arth import Add

from arth import Sub

num1=float(input("Enter first Number : "))

num2=float(input("Enter second Number : "))

print("Addition is : ",Add(num1,num2))

print("Subtraction is : ",Sub(num1,num2))

Output:

Enter first Number : 4

Enter second Number : 6

('Addition is : ', 10.0)


('Subtraction is : ', -2.0)

24. Python program to read a file and capitalize the first letter of every word in the file.

program:

First create a file with name file1.txt


file1.txt contains data
hai
hello
welcome to python lab

program:

fname = open('file1.txt','r')
for line in fname:
l=line.title()
print(l)

output:

>>>
Hai

Hello

Welcome To Python Lab


25. Write a script named copyfile.py. This script should prompt the user for the names of two
text files. The contents of the first the second file

program:

file1.txt:
hai
hello
welcome to python lab

Create an empty file file2.txt

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"))

print("power value is:",power(x,n))

Output:

>>>

enter x value4

enter n value3

('power value is:', 64)


27. Python program to read the contents of a file in reverse order.

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()

# display the sorted words

print("The unique words in alphabetical order are:")


for word in words:
if word in lst:
continue
else:
lst.append(word)
print(word)

Output:

Enter file name: file.txt


The unique words in alphabetical order are:
This
is
program
python
to
welcome
29. Python programs to demonstrate functions
program:

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:

welcome to python lab


python is easy to use and easy to learn
('sum is=', 7)
('sum is=', 34)
('sum is=', 144)
('sum is=', 2)
31. Python program to create a class in which one method accepts a string from the user and
another prints it.
program:

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:

enter stringwelcome to python lab


('reverse of string is:', 'lab python to welcome')

You might also like