Python Lab Manual r20
Python Lab Manual r20
PYTHON PROGRAMMING
LABORATORY MANUAL
IB.Tech, II Semester
Common to CSE , AIDS (R20)
(2020– 2023 Batch)
Academic Year:2022-2023
WEST GODAVARI INSTITUTE OF SCIENCE AND ENGINEERING
Prakasaraopalem, Avapadu, Tadepalligudem, W.G.Dist
PYTHON LABORATORY
VISION & MISSION
PEO PEO
No. Description
PEO 1 Develop a solid foundation in Mathematics, Science and Technology to
solve
Computer Science and Engineering problems.
PEO 2 Identify, analyze and apply core engineering concepts to develop novel
products
and solutions for real life problems.
PEO 3 Pursue higher studies, research & development and other creative efforts in
science
& technology and keep abreast of latest technological developments.
PEO 4 Inculcate professional and ethical attitude, effective communication skills
andteam spirit and leadership qualities.
PEO 5 Contribute to the needs of the society in solving technical problems using
Computer Science and Engineering principles, tools and practices.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON LABORATORY
I B. Tech. II Semester CSE (R20) PROGRAM OUTCOMES
POs PO STATEMENT
GENERAL INSTRUCTIONS:
1. The experiments have been designed to be performed within the
3-hour laboratorytime.
2. To successfully complete the experiment in one lab turn,
come prepared to the laboratory.
3. Read the experiment in advance.
4. To Install python lab software.
5. Open the Idle shell and go to file menu to open new script.
6. In the new script to write python programs. And save it go run.
7. Record stepwise observe the outputs for each program.
8. Get the observation signed by the instructor.
9. Always take safety precautions with using computers.
PYTHON LAB MANUAL R20 I-IISEM
1. Write a program that asks the user for a weight in kilograms and converts
it to pounds. There are 2.2 pounds in a kilogram.
Code:
kilograms=float(input("Enter Weight in Kilograms: "))
pounds=2.2*kilograms
print("Weight in Pounds: ",pounds)
OUTPUT 1:
Enter Weight in Kilograms: 600
Weight in Pounds: 1320.
2. Write a program that asks the user to enter three numbers (use three
separate input statements). Create variables called total and average that hold
the sum and average of the three numbers and print out the values of total
and average.
Code:
OUTPUT 2:
Enter First Number: 50
Enter Second Number: 65
Enter Third Number: 78
Total= 193
Average= 64.33333333333333
3.) Write a program that uses a for loop to print the numbers 8, 11, 14, 17,
20, . . . , 83, 86, 89.
Code:
for i in range(8,90,3):
print(i,end=" ")
OUTPUT :
8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89
4.) Write a program that asks the user for their name and how many times to
print it. The program should print out the user’s name the specified number
of times.
Code:
OUTPUT 4:
Enter your Name: ANIL
Enter how many times you want to print: 9
ANIL
ANIL
ANIL
ANIL
ANIL
ANIL
ANIL
ANIL
5. )Use a for loop to print a triangle like the one below. Allow the user to
specify how high the triangle should be.
*
**
***
****
Code:
n=int(input("Enter the height of the triangle: "))
for i in range(1,n+1):
for j in range(i):
print("*",end="")
print()
OUTPUT:
*
**
***
****
*****
******
6. Generate a random number between 1 and 10. Ask the user to guess the
number and print a message based on whether they get it right or not.
Code:
import random
n=random.randint(1,10)
usernumner=int(input("Enter a number between 1 to 10(inclusive): "))
if(n==usernumner):
print("Your Guess is Right")
else:
print("Your Guess is Wrong")
print("Random Number: ",n)
OUTPUT :
Enter a number between 1 to 10(inclusive): 5
Your Guess is Wrong
Random Number: 10
7.) Write a program that asks the user for two numbers and prints Close if the
numbers are within .001 of each other and Not close otherwise.
Code:
OUTPUT 7:
Enter number 1 : 18.098
Enter number 2 : 30.990
Not Close
8. )Write a program that asks the user to enter a word and prints out whether
that word contains any vowels.
Code:
word=input("Enter a Word: ")
vowel='aeiouAEIOU'
flag=0
for i in vowel:
if i in word:
flag=1
break
if flag==1:
print("Word Contain Vowel")
else:
print("Word not Contain Vowel")
OUTPUT 8:
Enter a Word: CRY
Word not Contain Vowel
9.) Write a program that asks the user to enter two strings of the same length.
The program should then check to see if the strings are of the same length. If
they are not, the program should print an appropriate message and exit. If
they are of the same length, the program should alternate the characters of
the two strings. For example, if the user enters abcde and ABCDE the
program should print out AaBbCcDdEe.
Code:
s1=input("Enter First String: ")
s2=input("Enter Second String: ")
if(len(s1)= =len(s2)):
print("String are with same length")
result=''
for i in range(len(s1)):
result=result+(s2[i]+s1[i])
print(result)
else:
print("String are with different length")
OUTPUT 9:
Enter First String: abcdef
Enter Second String: ABCDEF
String are with same length
AaBbCcDdEeFf
10. Write a program that asks the user for a large integer and inserts commas
into it according to the standard American convention for commas in large
numbers. For instance, if the user enters 1000000, the output should be
1,000,000.
Code:
number=int(input("Enter a Long Number: "))
print("{:,}".format(number))
OUTPUT :
Enter a Long Number: 18500005432300
18,500,005,432,30
11.) In algebraic expressions, the symbol for multiplication is often left out,as
in 3x+4y or 3(x+5).Computers prefer those expressions to includethe
multiplication symbol, like 3*x+4*y or 3*(x+5).Write a program that asks the
user for an algebraic expression and theninserts multiplication symbols where
appropriate.
CODE:
s=input("Enter algebraic expression: ")
l=list(s)
result=''
i=0
while(i<len(l)):
if l[i]=='(':
index=l.index(')')
s2=''.join(l[i:index+1])
result=result+'*'+s2
i=i+len(s2)
elif l[i].isalpha():
result=result+'*'+l[i]
i=i+1
else:
result=result+l[i]
i=i+1
print(result)
OUTPUT:
enter algebraic expression:3x+4y
3*x+y*y
enter algebraic expression:3(x+5)
3*(x+5)
CODE:
import random
l=[]
for i in range(20):
l.append(random.randint(1,100))
print("List: ",l)
print("Average: ",
round(sum(l)/len(l),2))
print("Largest Value in List: ",max(l))
print("Smallest Value in List: ",min(l))
l1=sorted(l)
print( " Second Largest Value in List: ",l1[-2])
print("Smallest Value in List: ",l1[1])
count=0
for i in l:
if i%2==0:
count+=1
print("Number of Even Numbers in the list: ",count)
OUTPUT:
List: [69, 11, 20, 55, 7, 33, 94, 38, 42, 82, 26, 32, 15, 78, 81, 78, 57, 22, 50, 46]
Average: 46.8
Largest Value in List: 94
Smallest Value in List: 7
Second Largest Value in List: 82
Smallest Value in List: 11
Number of Even Numbers in the list: 12
13. Write a program that asks the user for an integer and creates a list that
consists of the factors of that integer.
CODE:
n=int(input("Enter a number: "))
l=[]
for i in range(1,n+1):
if(n%i==0):
l.append(i)
print(l)
OUTPUT:
Enter a number: 4
[1, 2, 4]
14. Write a program that generates 100 random integers that are either 0 or
1.Then find the longest run of zeros, the largest number of zeros in a row.For
instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
CODE:
import random
x=[]
for i in range(100):
x.append(random.randint(0,1))
maxzero=0
count=0
for i in range(len(x)):
if(x[i]==0):
count=count+1
if(i==len(x)-1):
if(count>maxzero):
maxzero=count
if(x[i]==1):
if(count>maxzero):
maxzero=count
count=0
print("Longest run of Zeros in a row is",maxzero)
OUTPUT:
Longest run of Zeros in a row is 7
15. Write a program that removes any repeated items from a list so that each
item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become
[1,2,3,4,0].
CODE:
l=list(map(int,input("Enter the elements into list with duplication: ").split(',')))
s=[]
for i in l:
if i not in s:
s.append(i)
print(s)
OUTPUT:
Enter the elements into list with duplication: 1,1,2,56,78,56,1
[1, 2, 56, 78]
16. Write a program that asks the user to enter a length in feet. The program
should then give the user the option to convert from feet into inches, yards,
miles, millimeters, centimeters, meters, or kilometers. Say if the user enters a
1, then the program converts to inches, if they enter a 2, then the program
converts to yards, etc. While this can be done with if statements,it is much
shorter with lists and it is also easier to add new conversions if you use lists.
CODE:
feet=int(input("Enter feet: "))
opt=int(input("enter choice 1:inches 2:yards 3:miles 4:millimeters 5:centimeters 6:meters
7:kilometers --->"))
l=[round(feet*12,3),round(feet*0.333,3),round(feet*0.000189,3),round(feet*304.8,3),\
round(feet*30.48,3),round(feet*0.305,3),round(feet*0.000305,3)]
print(l[opt-1])
OUTPUT:
enter feet:6
enter choice1:inches 2:yards 3:miles 4:millimetres 5:centimeters 6:meters 7:kilometres --→ 7
0.02
OR
PROGRAM2:
CODE:
feet=int(input("Enter feet:"))
opt=int(input("enter choice 1:inches 2:yards 3:miles 4:millimeters 5:centimeters 6:meters
7:kilometers --->"))
if(opt==1):
print(round(feet*12,3))
elif(opt==2):
print(round(feet*0.333,3))
elif(opt==3):
print(round(feet*0.00189,3))
elif(opt==4):
print(round(feet*304.8,3))
elif(opt==5):
print(round(feet*30.48,3))
elif(opt==6):
print(round(feet*0.305,3))
elif(opt==7):
print(round(feet*0.000305,3))
OUTPUT:
enter feet:6
enter choice1:inches 2:yards 3:miles 4:millimetres 5:centimeters 6:meters 7:kilometres --→ 7
0.02
17. Write a function called sum_digits that is given an integer num and
returns the sum of the digits of num.
CODE:
def sum_digits(num):
sum=0
while(num>0):
sum=sum+num%10
num=num//10
return sum
x=int(input("Enter a number: "))
s=sum_digits(x)
print("Sum of digits: ",s)
OUTPUT:
Enter a number: 153
Sum of digits: 9
18. Write a function called first_diff that is given two strings and returns the
first location in which the strings differ. If the strings are identical, it should
return -1.
CODE:
def first_diff(s1,s2):
if(s1==s2):
return -1
else:
if len(s1)==len(s2):
for i in range(len(s1)):
if s1[i]!=s2[i]:
return (i+1)
s1=input("Enter string 1: ")
s2=input("Enter string 2: ")
x=first_diff(s1,s2)
if(x== -1):
print("strings are identical")
else:
print("first difference occurs at location :",x)
OUTPUT:
Enter string 1: apple
Enter string 2: apvle
first difference occurs at location : 3
OUTPUT:
Enter an integer: 14
factors count is 4
20. Write a function called is_sorted that is given a list and returns True if the
list is sorted and False otherwise.
CODE:
def is_sorted(l):
x=l[:]
x.sort()
if l==x:
return True
else
return False
l=list(input("Enter list items : ").split())
print(is_sorted(l))
OUTPUT:
Enter list items : 34,56,78,99
True
21. Write a function called root that is given a number x and an integer n and
returns x1/n. In the function definition, set the default value of n to 2.
CODE:
def root(x,n=2):
return (x**(1/n))
x=int(input("Enter 'x' value: "))
n=int(input("Enter 'n' value: "))
ans1=root(x,n)
ans2=root(x)
print("Root value with n value: ",ans1)
print("Root Value with out n value (Default 2): ",ans2)
OUTPUT:
Enter 'x' value: 16
Enter 'n' value: 4
Root value with n value: 2.0
Root Value with out n value (Default 2): 4.0
22. Write a function called primes that is given a number n and returns a list
of the first n primes. Let the default value of n be 100.
CODE:
def printprime(n=100):
l=[]
x=2
while(len(l)<n):
for i in range(2,int(x**0.5)+1):
if(x%i==0):
break
else:
l.append(x)
x=x+1
return(l)
n=int(input("Enter no of primes wanted: "))
s=printprime(n)
print("List of first",n,"primes:",s)
j=printprime()
print("List of first 100 primes:",j)
OUT PUT:
Enter no of primes wanted: 10
List of first 10 primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
List of first 100 primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277,
281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
521, 523, 541]
23.Write a function called merge that takes two already sorted lists of possibly
different lengths, and merges them into a single sorted list. (a) Do this using
the sort method. (b) Do this without using the sort method.
# a)Do this using the sort method
CODE:
OUT PUT:
Enter the sorted list 1:1 4 6 8 9
Enter the sorted list 2:2 6 8 9 90
After merge the list is: [1, 2, 4, 6, 6, 8, 8, 9, 9, 90]
if not L1:
return L2
elif not L2:
return L1
result=[]
i=0
j=0
for k in range(len(L1)+len(L2)):
if L1[i]<=L2[j]:
result.append(L1[i])
if i<len(L1)-1:
i+=1
else:
result+=L2[j:] #when the last element in L1 is reached,
break #append the rest of L2 to result.
else:
result.append(L2[j])
if j<len(L2)-1:
j+=1
else:
result+=L1[i:] #When the last element in L2 is reached,
break #append the rest of L1 to result.
return result
l1=list(map(int,input("Enter the sorted list 1:").split()))
l2=list(map(int,input("Enter the sorted list 2:").split()))
s=merge_lists(l1,l2)
print("After merge the list is :",s)
OUT PUT:
24. Write a program that asks the user for a word and finds all the smaller
words that can be made from the letters of that word. The number of
occurrences of a letter in a smaller word can’t exceed the number of
occurrences of the letter in the user’s word.
CODE:
OUT PUT:
Enter a word: CSE
CS CE SC SE EC ES
25. Write a program that reads a file consisting of email addresses, each on its
own line. Your program should print out a string consisting of those email
addresses separated by semicolons.
CODE:
print('{}'.format(Lines[line].strip()))
else:
print('{}'.format(Lines[line].strip()),end=";")
OUT PUT:
26. Write a program that reads a list of temperatures from a file called
temps.txt, converts those temperatures to Fahrenheit, and writes the results to
a file called ftemps.txt.
CODE:
OUT PUT:
27. Write a class called Product. The class should have fields called name,
amount, and price, holding the product’s name, the number of items of that
product in stock, and the regular price of the product. There should be a
method get_price that receives the number of items to be bought and returns
a the cost of buying that many items, where the regular price is charged for
orders of less than 10 items, a 10% discount is applied for orders of between
10 and 99 items, and a 20% discount is applied for orders of 100 or more
items. There should also be a method called make_purchase that receives the
number of items to be bought and decreases amount by that much.
CODE:
class product:
def _init_(self,name,total_items,price):
self.name = name
self.total_items = total_items
self.price = price
Actual_cost=self.price*number_to_be_bought
print('Actual_cost is=',Actual_cost)
discount = 20
p=(100-discount)/100*self.price
cost=p*number_to_be_bought
print('Final costs(Discount cost20%) = ',cost,)
print("you save=",Actual_cost-cost,"Rupes")
OUT PUT:
Final costs = 35
A 10% discount is applied for orders of between 10 and 99 items
A 20% discount is applied for orders of 100 or more item
28. Write a class called Time whose only field is a time in seconds. It should
have a method called convert_to_minutes that returns a string of minutes and
seconds formatted as in the following example: if seconds is 230, the method
should return '5:50'. It should also have a method called convert_to_hours
that returns a string of hours, minutes, and seconds formatted analogously to
the previous method.
CODE:
class Time:
def __init__(self,sec):
self.sec=sec
def convert_to_minutes(self):
n=self.sec
minutes=n//60
seconds=n%60
return(str(minutes)+":"+str(seconds))
def convert_to_hours(self):
n=self.sec
hours=n//3600
minutes=(n//60)%60
seconds=n%60
return(str(hours)+":"+str(minutes)+":"+str(seconds))
a=int(input("Enter seconds: "))
c=Time(a)
print("Time in minutes:seconds format --->",c.convert_to_minutes())
print("Time in hours:minutes:seconds format --->",c.convert_to_hours())
OUT PUT:
29. Write a class called Converter. The user will pass a length and a unit when
declaring an object from the class— for example, c = Converter(9,'inches').
The possible units are inches, feet, yards, miles, kilometers, meters,
centimeters, and millimeters. For each of these units there should be a method
that returns the length converted into those units. For example, using the
Converter object created above, the user could call c.feet() and should get 0.75
as the result.
CODE:
class Converter:
def __init__(self,length,unit):
self.length=length
self.unit=unit
def feet(self):
if(self.unit=='feet'):
return self.length
elif(self.unit=='inches'):
return self.length/12
elif(self.unit=='yards'):
return self.length/0.333
elif(self.unit=='miles'):
return self.length/0.000189
elif(self.unit=='millimeters'):
return self.length/304.8
elif(self.unit=='centimeters'):
return self.length/30.48
elif(self.unit=='meters'):
return self.length/0.305
elif(self.unit=='kilometers'):
return self.length/0.000305
def inches(self):
if(self.unit=='feet'):
return self.length*12
elif(self.unit=='inches'):
return self.length
elif(self.unit=='yards'):
return self.length*36
elif(self.unit=='miles'):
return self.length*63360
elif(self.unit=='millimeters'):
return self.length*0.0393701
elif(self.unit=='centimeters'):
return self.length*0.393701
elif(self.unit=='meters'):
return self.length*39.3701
elif(self.unit=='kilometers'):
return self.length*39370.1
def yards(self):
if(self.unit=='feet'):
return self.length*0.333333
elif(self.unit=='inches'):
return self.length*0.0277778
elif(self.unit=='yards'):
return self.length
elif(self.unit=='miles'):
return self.length*1760
elif(self.unit=='millimeters'):
return self.length*0.00109361
elif(self.unit=='centimeters'):
return self.length*0.0109361
elif(self.unit=='meters'):
return self.length*1.09361
elif(self.unit=='kilometers'):
return self.length*1093.61
def miles(self):
if(self.unit=='feet'):
return self.length*0.000189394
elif(self.unit=='inches'):
return self.length*63360
elif(self.unit=='yards'):
return self.length*0.027777728
elif(self.unit=='miles'):
return self.length
elif(self.unit=='millimeters'):
return self.length/1609344
elif(self.unit=='centimeters'):
return self.length/160934.4
elif(self.unit=='meters'):
return self.length/1609.344
elif(self.unit=='kilometers'):
return self.length/1.609
def kilometers(self):
if(self.unit=='feet'):
return self.length/3280.84
elif(self.unit=='inches'):
return self.length/39370.1
elif(self.unit=='yards'):
return self.length/1093.61
elif(self.unit=='miles'):
return self.length/0.621371
elif(self.unit=='millimeters'):
return self.length/1000000
elif(self.unit=='centimeters'):
return self.length/100000
elif(self.unit=='meters'):
return self.length/1000
elif(self.unit=='kilometers'):
return self.length
def meters(self):
if(self.unit=='feet'):
return self.length/3.28084
elif(self.unit=='inches'):
return self.length/39.3701
elif(self.unit=='yards'):
return self.length/1.09361
elif(self.unit=='miles'):
return self.length/0.000621371
elif(self.unit=='millimeters'):
return self.length/1000
elif(self.unit=='centimeters'):
return self.length/100
elif(self.unit=='meters'):
return self.length
elif(self.unit=='kilometers'):
return self.length/0.001
def centimeters(self):
if(self.unit=='feet'):
return self.length/0.0328084
elif(self.unit=='inches'):
return self.length/0.393701
elif(self.unit=='yards'):
return self.length/0.0109361
elif(self.unit=='miles'):
return self.length*160934
elif(self.unit=='millimeters'):
return self.length/10
elif(self.unit=='centimeters'):
return self.length
elif(self.unit=='meters'):
return self.length*100
elif(self.unit=='kilometers'):
return self.length*100000
def millimeters(self):
if(self.unit=='feet'):
return self.length*304.8
elif(self.unit=='inches'):
return self.length/0.0393701
elif(self.unit=='yards'):
return self.length/0.00109361
elif(self.unit=='miles'):
return self.length*1609340
elif(self.unit=='millimeters'):
return self.length
elif(self.unit=='centimeters'):
return self.length*10
elif(self.unit=='meters'):
return self.length*100
elif(self.unit=='kilometers'):
return self.length*1000000
CODE:
class power:
def pow(self,x,n):
print("pow(",x,",",n,") =",x**n)
p=power()
x=int(input("Enter 'x' value : "))
n=int(input("Enter 'n' value : "))
p.pow(x,n)
OUT PUT:
32. Write a program that opens a file dialog that allows you to select a text
file. The program then displays the contents of the file in a textbox.
CODE:
from tkinter import filedialog
from tkinter import Tk
from tkinter import *
root = Tk()
root.fileName = filedialog.askopenfilename(filetypes=(("Text Files",".txt"),("All Files","*.*")))
text1 = open(root.fileName).read()
T = Text(root, height=25, width=80)
T.pack()
T.insert(END,text1) #END (or “end”) corresponds to the position just after the last character in
the buffer.
root.mainloop()
OUT PUT:
OUT PUT: