Professional Documents
Culture Documents
Python Lab Manual
Python Lab Manual
LAB MANUAL
Prepared by
+----+---+
| | |
| | |
| | |
+----+---+
| | |
| | |
| | |
+----+---+
###
#####
#######
UP TO 12 HASHES
Write a script that reads the current time and converts it to a time of day in hours,
minutes, and seconds, plus the number of days since the epoch.
8 .Given n+r+1 <= 2r . n is the input and r is to be determined. Write a program which 12-13
computes minimum value of r that satisfies the above
9 Write a program that evaluates Ackermann function 13-14
10 Choose any 3 built-in string functions of C language. Implement them on your own in 14-16
Python. You should not use string related Python built-in functions
10.1 Python Program to find the Larger String without Using Built-in Functions 14-15
10.2 Reverse string without using function in Python 15
10.3 Python program to calculate length of a String without using len() function 15-16
11 Given a text of characters, Write a program which counts number of vowels, 16-18
consonants and special characters
12 Given a word which is a string of characters. Given an integer say ‘n’, Rotate each 18-19
character by ‘n’ positions and print it. Note that ‘n’ can be positive or negative
13 Given rows of text, write it in the form of columns 19
14 The mathematician Srinivasa Ramanujan found an infinite series that can be used to 20-21
generate a numerical approximation of 1/ π : Write a function called estimate_pi
that uses this formula to compute and return an estimate of π.
It should use a while loop to compute terms of the summation until the last term is
smaller than
1e-15 (which is Python notation for 10 -15). You can check the result by comparing
it to math.pi
15 Given a page of text. Count the number of occurrences of each latter (Assume case 21-23
insensitivity and don’t consider special characters).
16 Write a program that reads a file, breaks each line into words, strips whitespace and 24
punctuation from the words, and converts them to lowercase
17 Design a Python script to determine the difference in date for given two dates in 24-25
YYYY:MM:DD format(0 <= YYYY <= 9999, 1 <= MM <= 12, 1 <= DD <= 31) following the
leap year rules
18 Design a Python Script to determine the time difference between two given times in 25
HH:MM:SS format.( 0 <= HH <= 23, 0 <= MM <= 59, 0 <= SS <= 59).
19 Write a program that has a class point.Define another class Location which has two 25-26
objects(Location and Designation)of class Point.Also define a function in Location that
prints the reflection of Destination on the x axis.
20 Write a program that creates two sets—squares and cubes in range 1-10.Demonstrate 27
the use of update(),pop(),remove(),add(),clear() functions
21 Write a program to sum the series 1/1!+4/2!+27/3!+………….. 28
22 Write a python program that uses docstrings and variable-length arguments to add 29
the values passed to the function.
23 Write a python program that greets a person 29-30
24 Write a program that finds whether a given character is present in a string or not.In 30
case it is present it prints the index at which it is present.Do not use built-in find
functions to search the character.
25 Write a python program that converts strings of all uppercase characters into strings 31
of all lowercase characters using the map() function.
26 Write a program that has a list of both positive and negative numbers.Create another 31
list using filter() that has only positive values.
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
0 0 3 1.5
Course Objectives:
+----+---+
| | |
| | |
| | |
+----+---+
| | |
| | |
| | |
+----+---+
###
#####
#######
UP TO 12 HASHES
7. The time module provides a function, also named time that returns the current Greenwich Mean
Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the
epoch is 1 January 1970. >>> import time >>> time.time() 1437746094.5735958
Write a script that reads the current time and converts it to a time of day in hours, minutes, and
seconds, plus the number of days since the epoch.
8. Given n+r+1 <= 2r . n is the input and r is to be determined. Write a program which computes
minimum value of r that satisfies the above.
9. Write a program that evaluates Ackermann function
10. Choose any 3 built-in string functions of C language. Implement them on your own in Python. You
should not use string related Python built-in functions
10.1)Python Program to find the Larger String without Using Built-in Functions
11. Given a text of characters, Write a program which counts number of vowels, consonants and
special characters.
12. Given a word which is a string of characters. Given an integer say ‘n’, Rotate each character by ‘n’
positions and print it. Note that ‘n’ can be positive or negative.
14. The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a
numerical approximation of 1/ π : Write a function called estimate_pi that uses this formula to
compute and return an estimate of π.
It should use a while loop to compute terms of the summation until the last term is smaller than
1e-15 (which is Python notation for 10 -15). You can check the result by comparing it to math.pi
15 Given a page of text. Count the number of occurrences of each latter (Assume case insensitivity
and don’t consider special characters).
16 Write a program that reads a file, breaks each line into words, strips whitespace and punctuation
from the words, and converts them to lowercase
17. Design a Python script to determine the difference in date for given two dates in YYYY:MM:DD
format(0 <= YYYY <= 9999, 1 <= MM <= 12, 1 <= DD <= 31) following the leap year rules
18. Design a Python Script to determine the time difference between two given times in HH:MM:SS
format.( 0 <= HH <= 23, 0 <= MM <= 59, 0 <= SS <= 59).
19. Write a program that has a class point.Define another class Location which has two
objects(Location and Designation)of class Point.Also define a function in Location that prints the
reflection of Destination on the x axis.
20. Write a program that creates two sets—squares and cubes in range 1-10.Demonstrate the use of
update(),pop(),remove(),add(),clear() functions
21. Write a program to sum the series 1/1!+4/2!+27/3!+…………..
22. Write a python program that uses docstrings and variable-length arguments to add the values
passed to the function.
24. Write a program that finds whether a given character is present in a string or not.In case it is
present it prints the index at which it is present.Do not use built-in find functions to search the
character.
25. Write a python program that converts strings of all uppercase characters into strings of all
lowercase characters using the map() function
26. Write a program that has a list of both positive and negative numbers.Create another list using
filter() that has only positive values
EXPERIMENT-1.1
1.1 OBJECTIVE:
Install Python Interpreter and use it to perform different Mathematical Computations. Try to do all
the operations present in a Scientific Calculator
INSTALLATION PROCESS:
The Python download requires about 25 Mb of disk space; keep it on your machine, in case you need
to re-install Python. When installed, Python requires about an additional 90 Mb of disk space.
Downloading
2.Click the Windows link (two lines below the Download Python 3.7.4 button). The following page
will appear in your browser
4.Move this file to a more permanent location, so that you can install Python (and reinstall it easily
later, if necessary).
5.Feel free to explore this webpage further; if you want to just continue the installation, you can
terminate the tab browsing this webpage.
Installing
If the Python Installer finds an earlier version of Python installed on your computer, the Install
Now message may instead appear as Upgrade Now (and the checkboxes will not appear).
2,Highlight the Install Now (or Upgrade Now) message, and then click it.
When run, a User Account Control pop-up window may appear on your screen. I could not capture its
image, but it asks, Do you want to allow this app to make changes to your device.
A new Python 3.7.4 (64-bit) Setup pop-up window will appear with a Setup Progress message and a
progress bar
During installation, it will show the various components it is installing and move the progress bar
towards completion. Soon, a new Python 3.7.4 (64-bit) Setup pop-up window will appear with
a Setup was successfuly message.
Verifying
.
1.2.PROGRAM:
print(number_1 + number_2)
print(number_1 - number_2)
print(number_1 * number_2)
12 + 12 =
24
12 - 12 =
1 12 * 12 =
2 144
12 / 12 =
1.0
EXPERIMENT-2
2.1 OBJECTIVE
| | |
| | |
| | |
+----+---+
| | |
| | |
| | |
+----+---+
else:
print(" ",end="")
print()
for i in range(n+1):
for j in range(n+2):
if i==n:
if j==0 or j==n+1 :
print("+",end='')
if j==n+1:
for k in range(n+1):
if k==n:
print("+",end='')
else:
print("-",end="")
else:
print("-",end="")
else:
if j==0 or j==n+1 :
print("|",end='')
if j==n+1:
for k in range(n+1):
if k==n:
print("|",end='')
else:
print(" ",end="")
else:
print(" ",end="")
print()
+---+---+
| | |
| | |
| | |
+---+---+
| | |
| | |
| | |
+---+---+
EXPERIMENT – 3
3.1.1 OBJECTIVE
Write a function that draws a Pyramid with # symbols
#
###
#####
####### UP TO 12 HASHES
3.1.2 PROGRAM
for i in range(1,n+1):
for s in range(n-i):
print(" ",end="")
for j in range(i):
print("#",end="")
for k in range(1,i):
print("#",end="")
print()
###
#####
#######
#########
###########
#############
###############
#################
###################
#####################
#######################
EXPERIMENT-4
4.1.2 PROGRAM
import turtle
import math
num=30
A=turtle.position()
side=50
x=(side/2)/math.sin(math.radians(180/num))
5.1 OBJECTIVE
5.2 PROGRAM
6.1.1 OBJECTIVE
for x in range(360):
pencolor(colors[x % 6])
width(x / 5 + 1)
forward(x)
left(20)
7.1.1 OBJECTIVE
The time module provides a function, also named time that returns the current Greenwich Mean
Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the
epoch is 1 January 1970. >>> import time >>> time.time() 1437746094.5735958
Write a script that reads the current time and converts it to a time of day in hours, minutes, and
seconds, plus the number of days since the epoch.
PROGRAM
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
mydate = int(time.time())
num_days = mydate // 3600 // 24
print(num_days, "days since epoch")
EXPERIMENT-8
8.1 OBJECTIVE
Given n+r+1 <= 2r . n is the input and r is to be determined. Write a program which computes
minimum value of r that satisfies the above
PROGRAM
# n+r+1<=2 power r
n=int(input(“ENTER ANY NUMBER:”))
for r in range(n//2):
if n+r+1 >= 2**r:
break
print("For the value of r=",r ,"n+r+1<=2 power will get satisfied" )
EXPERIMENT-9
9.1 OBJECTIVE
PROGRAM
A(m,n)=n+1 if m==0
Enter m value2
Enter n value1
A( 2, 1)
A( 1, A( 2, 0))
A( 1, A( 1, 1))
A( 1, A( 0, A( 1, 0)))
A( 1, A( 0, A( 0, 1)))
A( 1, A( 0, 2))
A( 0, A( 1, 2))
A( 0, A( 0, A( 1, 1)))
A( 0, A( 0, A( 0, A( 1, 0))))
A( 0, A( 0, A( 0, A( 0, 1))))
A( 0, A( 0, A( 0, 2)))
A( 0, A( 0, 3))
A( 0, 4)
EXPERIMENT-10.1
10.1.1 OBJECTIVE:
Choose any 3 built-in string functions of C language. Implement them on your own in Python. You
should not use string related Python built-in functions
A)Python Program to find the Larger String without Using Built-in Functions
10.1.2 PROGRAM
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
elif(count1==count2):
else:
print(string1)
EXPERIMENT-10.2
10.2.1 OBJECTIVE
10.2.2 PROGRAM:
my_string=("JNTUA")
str=""
for i in my_string:
str=i+str
print("Reversed string:",str)
EXPERIMENT-10.3
10.3.1 OBJECTIVE
10.3.2 PROGRAM:
counter = 0
for s in str:
counter = counter+1
Enter a string:234
EXPERIMENT-11
11.1 OBJECTIVE
Given a text of characters, Write a program which counts number of vowels, consonants and
special characters.
11.2 PROGRAM
def countCharacterType(str):
# characters
vowels = 0
consonant = 0
specialChar = 0
digit = 0
ch = str[i]
if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') ):
ch = ch.lower()
vowels = vowels+1
else:
consonant = consonant+1
digit = digit+1
else:
specialChar = specialChar+1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
# Driver function.
countCharacterType(str)
Vowels: 4
Consonant: 13
Digit: 3
Special Character: 3
EXPERIMENT-12
12.1 OBJECTIVE
Given a word which is a string of characters. Given an integer say ‘n’, Rotate each character by ‘n’
positions and print it. Note that ‘n’ can be positive or negative.
12.2 PROGRAM
def rotate(ip,d):
if d>=0:
Rsecond = ip[len(ip)-d : ]
else:
Lsecond = ip[-1*d :]
ip = input('Enter a word')
rotate(ip,d)
Enter a wordPYTHON
13.1 OBJECTIVE
13.2 PROGRAM
Import pandas as pd
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],'Address':['Delhi', 'Kanpur',
'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df = pd.DataFrame(data)
df["Name"]= df["Name"].str.lower()
print(df)
1 princi 24 Kanpur MA
14.1 OBJECTIVE
The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate
a numerical approximation of 1/ π : Write a function called estimate_pi that uses this formula to
compute and return an estimate of π.
It should use a while loop to compute terms of the summation until the last term is smaller than
1e-15 (which is Python notation for 10 -15). You can check the result by comparing it to math.pi
14.2 PROGRAM
import math
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n - 1)
result = n * recurse
return result
def estimate_pi():
total = 0
k=0
while True:
break
k=k+1
return 1 / total
print("Result = ",estimate_pi())
print("Pi = ",math.pi)
Result=3.141592653589793
Pi=3.141592653589793
EXPERIMENT-15
15.1 OBJECTIVE
Given a page of text. Count the number of occurrences of each latter (Assume case insensitivity and
don’t consider special characters).
15.2 PROGRAM
alphas = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C',
'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
with open(fname,'r') as f:
d = f.read()
for i in range(len(alphas)):
count = 0
for j in range(len(d)):
if d[j] == alphas[i]:
count = count+1
Occurence of letter a is 16
Occurence of letter b is 1
Occurence of letter c is 9
Occurence of letter d is 5
Occurence of letter e is 16
Occurence of letter f is 11
Occurence of letter g is 3
Occurence of letter h is 6
Occurence of letter i is 13
Occurence of letter j is 3
Occurence of letter k is 1
Occurence of letter l is 9
Occurence of letter m is 4
Occurence of letter n is 20
Occurence of letter o is 10
Occurence of letter p is 8
Occurence of letter q is 1
Occurence of letter r is 11
Occurence of letter s is 7
Occurence of letter t is 12
Occurence of letter u is 8
Occurence of letter v is 1
Occurence of letter x is 1
Occurence of letter y is 1
Occurence of letter z is 1
Occurence of letter A is 1
Occurence of letter B is 1
Occurence of letter C is 1
Occurence of letter D is 1
Occurence of letter E is 2
Occurence of letter F is 1
Occurence of letter G is 1
Occurence of letter H is 1
Occurence of letter I is 1
Occurence of letter J is 1
Occurence of letter K is 1
Occurence of letter L is 1
Occurence of letter M is 1
Occurence of letter N is 1
Occurence of letter O is 2
Occurence of letter P is 1
Occurence of letter Q is 1
Occurence of letter R is 1
def stripped_text(a_file):
new_text = []
fin = open(a_file)
stripped_line = line.lower().translate(str.maketrans("","")).split()
new_text += stripped_line
return new_text
a="p26.py"
print(stripped_text(a))
['def', 'stripped_text(a_file):', 'new_text', '=', '[]', 'fin', '=', 'open(a_file)', 'for', 'line', 'in', 'fin:',
'stripped_line', '=', 'line.lower().translate(str.maketrans("","")).split()', 'new_text', '+=',
'stripped_line', 'return', 'new_text', 'a="p26.py"', 'print(stripped_text(a))']
EXPERIMENT-17
17.1 OBJECTIVE
Design a Python script to determine the difference in date for given two dates in YYYY:MM:DD
format(0 <= YYYY <= 9999, 1 <= MM <= 12, 1 <= DD <= 31) following the leap year rules.
17.2 PROGRAM
import datetime
datetimeFormat = '%Y-%m-%d'
date1 = '2019-04-16'
date2 = '2019-03-10'
#print("Difference:", diff)
print("Days:", diff.days)
EXPERIMENT-18
18.1 OBJECTIVE
Design a Python Script to determine the time difference between two given times in HH:MM:SS
format.( 0 <= HH <= 23, 0 <= MM <= 59, 0 <= SS <= 59)
18.2PROGRAM
FMT = '%H:%M:%S'
EXPERIMENT-19
19.1 OBJECTIVE
Write a program that has a class point.Define another class Location which has two objects(Location
and Designation)of class Point.Also define a function in Location that prints the reflection of
Destination on the x axis.
19.2PROGRAM
class Point:
def__init__(self, x, y):
self.y=y
def get(self):
return(self.x,self.y)
class Location:
def__init__(self,x1,y1,x2,y2):
self.Source=Point(x1,y1)
self.Destination=Point(x2,y2)
def show(self):
print("Source = ",self.Source.get())
print("Destination = ",self.Destination.get())
def reflection(self):
self.Destination.x = -self.Destination.x
L=Location(1,2,3,4)
L.show()
L.reflection()
Source=(1,2)
Destination=(3,4)
20.1 OBJECTIVE
Write a program that creates two sets—squares and cubes in range 1-10.Demonstrate the use of
update(),pop(),remove(),add(),clear() functions
20.2PROGRAM
print("SQUARES : ",squares)
print("CUBES : ",cubes)
squares.update(cubes)
squares.add(11*11)
squares.add(11*11*11)
squares.remove(1331)
print("REMOVE : ",squares)
squares.clear()
print("CLEAR : ",squares)
UPDATE : {64, 1, 512, 4, 36, 8, 9, 16, 49, 81, 729, 343, 216, 25, 27, 125}
ADD : {64, 1, 512, 121, 4, 36, 8, 9, 16, 49, 81, 1331, 729, 343, 216, 25, 27, 125}
POP : 64
REMOVE : {1, 512, 121, 4, 36, 8, 9, 16, 49, 81, 729, 343, 216, 25, 27, 125}
CLEAR : set()
21.1 OBJECTIVE
21.2PROGRAM
def fact(n):
f=1
if(n==0 or n==1):
return 1
else:
for i in range(1,int(n+1)):
f=f*i
return f
s=0.0
for i in range(1,n+1):
s=s+(float(i**i)/fact(i))
print("Result :",s)
Result : 3.302525713102e+18
22.1 OBJECTIVE
Write a python program that uses docstrings and variable-length arguments to add the values
passed to the function
22.2 PROGRAM
def add(*args):
sum=0
for i in args:
sum+=i
return sum
print(add.__doc__)
print("SUM = ",add(25,30,45,50))
SUM = 150
EXPERIMENT-23
23.1 OBJECTIVE
23.2PROGRAM
def greet(name,mesg):
"""This Function Welcomes the person passed Whose name is passed as a parameter"""
EXPERIMENT-24
24.1 OBJECTIVE
Write a program that finds whether a given character is present in a string or not.In case it is present
it prints the index at which it is present.Do not use built-in find functions to search the character.
24.2 PROGRAM
def find_ch(s,c):
index=0
while(index<len(s)):
if s[index]==c:
return
else:
pass
index+=1
find_ch(str,ch)
25.1 OBJECTIVE
Write a python program that converts strings of all uppercase characters into strings of all lowercase
characters using the map() function.
25.2 PROGRAM
def to_lower(str):
return str.lower()
list1=["HELLO","WELCOME","TO","PYTHON"]
list2=list(map(to_lower,list1))
EXPERIMENT-26
26.1 OBJECTIVE
Write a program that has a list of both positive and negative numbers.Create another list using filter()
that has only positive values.
26.2PROGRAM
def is_positive(x):
if x>=0:
return x
num_list=[10, -20, 30, -40, 50, -60, 70, -80, 90, -100]
List = []