Python Lab Manual
Python Lab Manual
Lab Manual
for
Python Programming
R201225
Submitted By:
T N S KOTI MANI KUMAR
Assistant Professor
Department of Computer Science and Enginering
Sir C R Reddy College of Engineering
Submitted To:
Department of First Year Engineering
i
TABLE OF CONTENTS
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. 1
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. 1
3 Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, .
. . , 83, 86, 89. 2
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. 2
5 Use a for loop to print a triangle like the one below. Allow the user to specify
how high the triangle should be.
*
**
***
**** 3
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. 4
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. . 4
8 Write a program that asks the user to enter a word and prints out whether
that word contains any vowels. 5
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. 6
ii
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 num-
bers. For instance, if the user enters 1000000, the output should be 1,000,000
7
13 Write a program that asks the user for an integer and creates a list that con-
sists of the factors of that integer. 9
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. 10
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]. 11
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. 12
17 Write a function called sumdigits that is given an integer num and returns the
sum of the digits of num. 13
iii
18 Write a function called numberoffactors that takes an integer and returns
how many factors the number has. 14
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. 16
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. 17
23 Write a function called merge that takes two already sorted lists of possibly
different lengths, and merges them into a single sorted list. 18
23.1 Do this using the sort method . . . . . . . . . . . . . . . . . . . . . . . . . 18
23.2 Do this without using the sort method. . . . . . . . . . . . . . . . . . . . . 18
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. 19
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. 20
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. . 20
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 10for orders of between 10 and 99 items, and a 20100 or more
items. There should also be a method called makepurchase that receives the
number of items to be bought and decreases amount by that much. 21
iv
28 Write a class called Time whose only field is a time in seconds. It should have a
method called converttominutes 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 converttohours that returns
a string of hours, minutes, and seconds formatted analogously to the previous
method. 23
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, centime-
ters, and millimeters. For each of these units there should be a method that
returns the length converted into those units. For example, using the Con-
verter object created above, the user could call c.feet() and should get 0.75 as
the result. 24
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. 30
v
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.
PROGRAM:
OUTPUT:
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.
PROGRAM:
OUTPUT:
1
enter anumber c:4
9
3.0
3. Write a program that uses a for loop to print the numbers 8, 11, 14,
17, 20, . . . , 83, 86, 89.
PROGRAM:
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.
PROGRAM:
OUTPUT:
2
enter your name:python
enter how many times you want to print:4
python
python
python
python
5. Use a for loop to print a triangle like the one below. Allow the user
to specify how high the triangle should be.
*
**
***
****
PROGRAM:
OUTPUT:
3
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.
PROGRAM:
import random
n=random.randint(1,10)
usernumber=int(input("enter a number between 1 to 10:"))
if(n==usernumber):
print("your guess is right")
else:
print("your guess is wrong")
print("random number:",n)
OUTPUT:
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. .
PROGRAM:
4
print("Close")
else:
print("Not close")
OUTPUT:
8. Write a program that asks the user to enter a word and prints out
whether that word contains any vowels.
PROGRAM:
OUTPUT:
5
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 appro-
priate 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 AaB-
bCcDdEe.
PROGRAM:
OUTPUT:
6
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
PROGRAM:
n=int(input("Enter a number:"))
print("The number seperated with commas is:{:,}".format(n))
OUTPUT:
Enter a number:102012356
The number seperated with commas is:102,012,356
PROGRAM:
7
elif l[i].is alpha():
result=result+’*’+l[i]
i=i+1
else:
result=result+l[i]
i=i+1
print(result)
OUTPUT:
PROGRAM:
import random
numList=[]
for i in range(20):
numList.append(random.randint(1,100));
print("List is :",numList)
print("Average is :",sum(numList)/20)
print("Largest element is",sorted(numList)[-1],"and smallest element
is",sorted(numList)[0])
8
print("Second largest element is",sorted(numList)[-2],"and second smallest
element is",sorted(numList)[1])
count=0
for ele in numList:
if ele%2==0:
count+=1
print("Total number of even elements are :",count)
OUTPUT:
ist is : [50, 53, 2, 100, 59, 82, 72, 72, 2, 4, 4, 87, 62, 17, 11, 63, 39,
80, 20, 67]
Average is : 47.3
Largest element is 100 and smallest element is 2
Second largest element is 87 and second smallest element is 2
Total number of even elements are : 12
13. Write a program that asks the user for an integer and creates a list
that consists of the factors of that integer.
PROGRAM:
OUTPUT:
9
14. Write a program that generates 100 random integers that are ei-
ther 0 or 1. Then find the longest run of zeros, the largest num-
ber 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.
PROGRAM:
import random
l=[]
def my_list():
for j in range(0,100):
x=random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
zero_count = 0
for j in l:
if j==0:
c+=1
else:
if c > zero_count:
zero_count = c
c = 0
return zero_count
l = my_list()
print(largest_row_of_zeros(l))
OUTPUT:
10
[1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1,
1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1,
0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,
1, 0, 1]
6
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].
PROGRAM:
OUTPUT:
11
2
3
3
the list elements [1, 1, 1, 2, 3, 3] :
After removing duplicates list is [1, 2, 3]
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 kilo-
meters. 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.
PROGRAM:
12
kilometers]
print(convert[integer])
OUTPUT:
17. Write a function called sumdigits that is given an integer num and
returns the sum of the digits of num.
PROGRAM:
def sumdigits(num):
sum=0
num=num//10
while(num>0):
sum=sum+num%10
return sum
x=input("enter a number:")
s=int(x[0])+int(x[1])+int(x[2])
print("the sum of digits is:",s)
OUTPUT:
13
18. Write a function called numberoffactors that takes an integer and
returns how many factors the number has.
PROGRAM:
14
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:
PROGRAM:
def number_of_factors(num):
factors=0
for i in range(1,num+1):
if(num%i==0):
factors+=1
return factors
num=int(input("enter an integer"))
x=number_of_factors(num)
print("factors count is",x)
OUTPUT:
Enter an integer25
15
factors count is 3
PROGRAM:
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:
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.
PROGRAM:
def root(x,n):
return x**(1/n)
x=root(125,2)
16
print(x)
OUTPUT:
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.
PROGRAM:
OUTPUT:
17
23. Write a function called merge that takes two already sorted lists of
possibly different lengths, and merges them into a single sorted list.
PROGRAM:
OUTPUT:
PROGRAM:
def merge(l1,l2):
s1=len(l1)
s2=len(l2)
l=[]
i,j = 0,0
while i<s1 and j<s2:
if l1[i] < l2[j]:
l.append(l1[i])
i+=1
18
else:
l.append(l2[j])
j+=1
return (l+l1[i:]+l2[j:])
a=list(map(int, input ("Enter sorted list 1: ").split()))
b=list(map(int, input ("Enter sorted list 2: ").split()))
print("sorted list after merging: ",merge(a, b))
OUTPUT:
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.
PROGRAM:
OUTPUT:
19
25. Write a program that reads a file consisting of email addresses,
each on its own line. Your program should print out a string con-
sisting of those email addresses separated by semicolons.
PROGRAM:
OUTPUT:
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. .
PROGRAM:
20
OUTPUT:
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 prod-
uct. There should be a method getprice 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 10for orders of between 10 and 99 items, and a 20100 or more
items. There should also be a method called makepurchase that re-
ceives the number of items to be bought and decreases amount by
that much.
PROGRAM:
class product:
def __init__(self, name, items, price):
self.name=name;
self.items=items
self.price=price
def getprice (self,n):
if n<10:
print ("Regular price is charged for you orders")
cost=n*self.price
print("If you place above 9 items you get 10% discount")
21
print("If you place above 99 items you get 20% discount")
elif n>=10 and n<100:
print ("10% discount is applied for you orders")
cost=n*self.price
discount= (cost* 10)/100
finalcost=cost-discount
print("Actual Cost: ", cost)
print("10% Discount: ", finalcost)
print("If you place above 99 items you get 20% discount")
print("Cost after 10% discount: ", discount)
else:
print ("20% discount is applied for you orders")
cost=n*self.price
discount= (cost*20)/100
finalcost=cost-discount
print("Actual Cost: ", cost)
print("20% Discount: ", discount)
print("Cost after 20% discount: ", finalcost)
def my_purchase (self, n):
if n<10:
print ("Regular price is charged for you orders")
cost=n*self.price
print("Final cost:", cost)
elif (n>=10) and (n<100):
print ("10% discount is applied for you orders")
cost=n*self.price
discount=(cost*10)/100
finalcost=cost-discount
print("Actual Cost: ", cost)
print("10% Discount: ", discount)
print("Final Cost after 10% discount: ", finalcost)
else:
print("20% discount is applied for you orders")
cost=n*self.price
discount=(cost*20)/100
finalcost=cost-discount
print("Actual Cost: ", cost)
print("20% Discount: ", discount)
print("Final Cost after 20% discount: ", finalcost)
p=product ("PEN", 200, 5)
n=int (input ("Enter Number of pens you want to buy: "))
22
p.getprice (n)
n=int (input ("Enter Number of pens you want to buy: "))
p.my_purchase (n)
OUTPUT:
28. Write a class called Time whose only field is a time in seconds. It
should have a method called converttominutes 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 converttohours that returns a string of hours, min-
utes, and seconds formatted analogously to the previous method.
PROGRAM:
class Time:
def __init__(self, sec):
self.sec=sec
def convert_to_minutes (self):
n=self.sec
minutes=n//60
seconds=n%60
23
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 ())
OUTPUT:
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 = Con-
verter(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.
PROGRAM:
class Converter:
def __init__(self, length, unit):
self.length = length
24
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 / 3
elif self.unit == ’miles’:
return self.length / 5280
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
25
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.000568182
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’:
26
return self.length * 1.609
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
27
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
len = int(input ("Enter length: "))
type=input("Enter unit type: inches, feet, yards,miles, millimeters,
centimeters, meters, kilometers->")
c=Converter (len, type)
print ("Length in Feet: ",round (c.feet (), 3))
print ("Length in Inches: ",round (c.inches (),3))
print ("Length in Yards: ", round (c.yards (), 3))
print ("Length in Miles: ",round (c.miles (),3))
print ("Length in Kilometers: ",round (c.kilometers(), 3))
print ("Length in Meters: ",round (c.meters(), 3))
print ("Length in Centimeters: ",round (c.centimeters(), 3))
print ("Length in Millimeters: ",round (c.millimeters (), 3))
OUTPUT:
Enter length: 6
Enter unit type: inches, feet, yards, miles, millimeters, centimeters,
meters,
kilometers--->
Length in Feet: 0.5
28
Length in Inches: 6
Length in Yards: 0.167
Length in Miles: 380160
Length in Kilometers: 0.0
Length in Meters: 0.152
Length in Centimeters:15.24
Length in Millimeters: 152.4
PROGRAM:
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)
OUTPUT:
PROGRAM:
class reverse:
29
def rev_sentence (self, sentence):
words = sentence.split(’ ’)
reverse_sentence= ’ ’.join(reversed(words))
print(reverse_sentence)
c=reverse()
c.rev_sentence (input ("Enter the string: "))
OUTPUT:
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.
PROGRAM:
OUTPUT:
30
33. Write a program to demonstrate Try/except/else.
PROGRAM:
try:
a=int (input ("Enter ’a’ value: "))
b=int (input ("Enter ’b’ value: "))
c=a//b
except ZeroDivisionError:
print ("Division can’t possible (b=0) ")
else:
print(" a//b Value: ", c)
OUTPUT:
31
Enter ’a’ value: 10
Enter ’b’ value: 2
a//b Value: 5
PROGRAM:
try:
a=int (input ("Enter ’a’ value: "))
b=int (input ("Enter ’b’ value: "))
c=a//b
except ZeroDivisionError:
print ("Division can’t possible (b=0) ")
else:
print(" a//b Value: ", c)
OUTPUT:
PROGRAM:
32
file.write(’hello friends how are you’)
finally:
file.close()
with open (’file2.txt’, ’w’) as file:
file.write(’hello friends how are you’)
OUTPUT:
33