Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 44

S V ENGINEERING COLLEGE

(Formerly S V Engineering College for Women)


Karakambadi Road, Tirupati - 517 507
Permanent Affiliation to JNTUA & Approved by AICTE
Recognized under section 2(f) & 12(B) of UGC act 1956.
Accredited by NAAC

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

19A05304-PYTHON PROGRAMMING LAB


Regulation – R19
Academic Year (2020 – 21)
Year / Semester: II / I

Prepared by

J.OMKAR REDDY , Assistant Professor

VISION OF THE INSTITUTE


To emerge as a Centre of Excellence with superior academic standards while
imparting quality education to develop contemporary innovative practices and
systems to become technologically empowered and ethically strong for the
betterment of the society.

MISSION OF THE INSTITUTE

 M1 : To create excellent infrastructure facilities and state-of-


the-art laboratories and incubation centers.

 M2 : To implement modern pedagogical methods in delivering


the academic programs with experienced and committed
faculty

 M3 : To develop a good rapport with the industries and


exchange information on latest technological
development, provide training for the faculty, staff and
students.

 M4 : To enhance leadership qualities among the youth and


enrich personality traits, promote patriotism and moral
values.

 M5 : To inculcate ethical values and environmental


consciousness through holistic education programs

VISION OF THE DEPARTMENT

To become a center of excellence that grooms globally competent and ethical


engineers with the talent for higher learning and research and the capability to
think critically of innovative solutions for diverse social needs.

MISSION OF THE DEPARTMENT


 M1:To impart quality technical education with strong foundations using
superior academic standards and well-equipped infrastructure.
 M2: To provide excellent pedagogies through qualified and highly skilled
faculty who are trained on a regular basis.
 M3:To establish research labs and a center of excellence that will nurture
the technical skills by training them with state of art technology required for
the industry.
 M4:To inculcate professional and ethical values in the students along with
leadership qualities so that they are well equipped to handle the dynamic
and diverse challenges they will face as engineers.

Program Educational Objectives

The program educational objectives of the Computer Science and Engineering


program describe accomplishments that graduates are expected to attain after 3
to 5 years of graduation.

 PEO1:To exhibit strong fundamental concepts of Computer Science &


Engineering along with advanced knowledge on emerging technologies so that
they can devise solutions for real time & social issues.
 PEO2:To be employed, to pursue higher studies, to become entrepreneurs
and also to have an excellent aptitude for research.
 PEO3:To be technically sound, socially acceptable and ethical professionals
with global competence.
 PEO4:To be young leaders with the capability to lead teams with good
communication skills and excellence in social awareness.

Program Specific Outcomes


 PSO1:An ability to get an employment in Computer Science and Engineering
field and related software industries.
 PSO2:An ability to participate in competitive examinations and enable them
to pursue higher education.
Program Outcomes

 PO1:Engineering knowledge: Apply knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization for the solution
of complex engineering problems.
 PO2:Problem analysis: Identify, formulate, research literature, and
analyses complex engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering
sciences.
 PO3:Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that meet
the specified needs with appropriate consideration for public health and
safety, and cultural, societal, and environmental considerations.
 PO4:Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
 PO5:Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
 PO6:The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal, and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
 PO7:Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.
 PO8:Ethics:Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
 PO9:Individual and team work: Function effectively as an individual, and
as a member or leader in diverse teams, and in multidisciplinary settings.
 PO10:Communication: Communicate effectively on complex engineering
activities with the engineering community and with the society at large, such
as being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions
 PO11:Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these
to one’s own work, as a member and leader in a team, to manage projects
and in multidisciplinary environments.
 PO12:Life-long learning: Recognize the need for, and have the preparation
and ability to engage in independent and life-long learning in the broadest
context of technological change.
INDEX

S.NO NAME OF THE PROGRAM PAGE –


NUMBERS
1 Install Python Interpreter and use it to perform different Mathematical Computations. 1-5
Try to do all the operations present in a Scientific Calculator
2 Write a function that draws a grid like the following: 5-7

+----+---+

| | |

| | |

| | |

+----+---+

| | |

| | |

| | |

+----+---+

3 3 Write a function that draws a Pyramid with # symbols 7-8

###

#####

#######

UP TO 12 HASHES

4 Using turtles concept draw a wheel of your choice. 9

5 Write a program that draws Archimedean Spiral. 10

6 Write a python program that draws a spiral by using turtle. 11


7 The time module provides a function, also named time that returns the current 12
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 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

B. Tech II-I Sem. (CSE) L T P C

0 0 3 1.5

19A05304-PYTHON PROGRAMMING LABORATORY

Course Objectives:

 To train the students in solving computational problems

 To elucidate solving mathematical problems using Python programming language

 To understand the fundamentals of Python programming concepts and its applications.

 To understand the object-oriented concepts using Python in problem solving.

Course out comes:

 Design solutions to mathematical problems.

 Organize the data for solving the problem.

 Develop Python programs for numerical and text based problems.

 Select appropriate programming construct for solving the problem.

 Illustrate object oriented concepts


1 Install Python Interpreter and use it to perform different Mathematical Computations. Try to do all
the operations present in a Scientific Calculator

2. Write a function that draws a grid like the following:

+----+---+

| | |

| | |

| | |

+----+---+

| | |

| | |

| | |

+----+---+

3 Write a function that draws a Pyramid with # symbols

###

#####

#######

UP TO 12 HASHES

4. Using turtles concept draw a wheel of your choice.

5. Write a program that draws Archimedean Spiral.

6. Write a python program that draws a spiral by using turtle.

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

10.2)Reverse string without using function in Python

10.3)Python program to calculate length of a String without using len() function

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.

13. Given rows of text, write it in the form of columns

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.

23. Write a python program that greets a person

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:

Python: Version 3.7.4

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

1. Click Python Download.

The following page will appear in your browser.

2.Click the Windows link (two lines below the Download Python 3.7.4 button). The following page
will appear in your browser

Python programming Lab 1 Dept. of CSE, SVEC


3.Click on the Download Windows x86-64 executable installer link under the top-left Stable
Releases.

The file should appear as

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.

6.Start the Installing instructions directly below.

Installing

1. Double-click the icon labeling the file python-3.7.4-amd64.exe.

A Python 3.7.4 (64-bit) Setup pop-up window will appear.

Python programming Lab 2 Dept. of CSE, SVEC


Ensure that the Install launcher for all users (recommended) and the Add Python 3.7 to
PATH checkboxes at the bottom are checked.

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.

3.Click the Yes button.

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.

Python programming Lab 3 Dept. of CSE, SVEC


4.Click the Close button.

Python should now be installed.

Verifying

To try to verify installation,


1. Navigate to the directory C:\Users\Pattis\AppData\Local\Programs\Python\Python37 (or
to whatever directory Python was installed: see the pop-up window for Installing step 3).
2. Double-click the icon/file python.exe.

The following pop-up window will appear.

.
1.2.PROGRAM:

number_1 = int(input('Enter your first number: '))

number_2 = int(input('Enter your second number: '))

print('{} + {} = '.format(number_1, number_2))

print(number_1 + number_2)

print('{} - {} = '.format(number_1, number_2))

print(number_1 - number_2)

print('{} * {} = '.format(number_1, number_2))

print(number_1 * number_2)

print('{} / {} = '.format(number_1, number_2))

Python programming Lab 4 Dept. of CSE, SVEC


print(number_1 / number_2)

1.3 INPUT AND OPUTPUT

Enter your first number: 12

Enter your second number: 12

12 + 12 =

24

12 - 12 =

1 12 * 12 =

2 144

12 / 12 =

1.0

EXPERIMENT-2

2.1 OBJECTIVE

Write a function that draws a grid like the following:


+----+---+

| | |

| | |

| | |

+----+---+

| | |

| | |

| | |

+----+---+

Python programming Lab 5 Dept. of CSE, SVEC


2.2 PROGRAM :

n=int(input("Enter the height of the grid: "))


for i in range(n+2):
for j in range(n+2):
if i==0 or i==n+1:
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()
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()

Python programming Lab 6 Dept. of CSE, SVEC


2.3 INPUT AND OPUTPUT

Enter the height of the grid: 3

+---+---+

| | |

| | |

| | |

+---+---+

| | |

| | |

| | |

+---+---+

EXPERIMENT – 3

3.1.1 OBJECTIVE
Write a function that draws a Pyramid with # symbols
#
###
#####
####### UP TO 12 HASHES

3.1.2 PROGRAM

Python programming Lab 7 Dept. of CSE, SVEC


n=int(input("ENTER ANY NUMBER"))

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

for s in range(n-i):

print(" ",end="")

for j in range(i):

print("#",end="")

if(i!=1 and j==i-1):

for k in range(1,i):

print("#",end="")

print()

3.2.1 INPUT AND OUTPUT


ENTER ANY NUMBER12

###

#####

#######

#########

###########

#############

###############

#################

###################

#####################

#######################

EXPERIMENT-4

Python programming Lab 8 Dept. of CSE, SVEC


4.1.1 OBJECTIVE

Using turtles concept draw a wheel of your choice

4.1.2 PROGRAM
import turtle
import math

num=30
A=turtle.position()
side=50
x=(side/2)/math.sin(math.radians(180/num))

#x contains the length of one spoke of wheel


ext=90+(180/num)
turtle.setheading(0)
for i in range(num):
turtle.forward(x)
turtle.left(ext)
turtle.forward(side)
turtle.left(ext)
turtle.forward(x)
turtle.setheading((i+1)*(360/num))
4.3 INPUT AND OUTPUT

Python programming Lab 9 Dept. of CSE, SVEC


EXPERIMENT – 5

5.1 OBJECTIVE

Write a program that draws Archimedean Spiral

5.2 PROGRAM

from turtle import *


from math import *
color("blue")
down()
for i in range(200):
t = i / 20 * pi
x = (1 + 5 * t) * cos(t)
y = (1 + 5 * t) * sin(t)
goto(x, y)
up()
done()

5.3 INPUT AND OUTPUT

Python programming Lab 10 Dept. of CSE, SVEC


EXPERIMENT-6.1

6.1.1 OBJECTIVE

Write a python program that draws a spiral by using turtle


PROGRAM

from turtle import *

colors = ['orange', 'red', 'pink', 'yellow', 'blue', 'green']

for x in range(360):

pencolor(colors[x % 6])

width(x / 5 + 1)

forward(x)

left(20)

INPUT AND OUTPUT

Python programming Lab 11 Dept. of CSE, SVEC


EXPERIMENT-7.1

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

from datetime import datetime


import time
now = datetime.now()

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

7.2.1 INPUT AND OUTPUT


Current Time = 05:52:02
18653 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" )

Python programming Lab 12 Dept. of CSE, SVEC


8.4 INPUT AND OUTPUT
ENETR ANY NUMBER:897

For the value of r= 0 n+r+1<=2 power will get satisfied

EXPERIMENT-9

9.1 OBJECTIVE

Write a program that evaluates Ackermann function

PROGRAM

def A(m, n, s ="% s"):


print(s % ("A(% d, % d)" % (m, n)))
if m == 0:
return n + 1
if n == 0:
return A(m - 1, 1, s)
n2 = A(m, n - 1, s % ("A(% d, %% s)" % (m - 1)))
return A(m - 1, n2, s)

print("A(m,n)=n+1 if m==0\n =A(m-1,1) if m>0 and n==0 \n


=A(m-1,A(m,n-1)) if m>0 and n>0 ")
m=int(input("Enter m value"))
n=int(input("Enter n value"))
print(A(m,n))

INPUT AND OUTPUT

A(m,n)=n+1 if m==0

=A(m-1,1) if m>0 and n==0

=A(m-1,A(m,n-1)) if m>0 and n>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))

Python programming Lab 13 Dept. of CSE, SVEC


A( 1, 3)

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

string1=”Good Computer Coding u can perform using python “;

string2=”It offers several topics”;

count1=0

count2=0

for i in string1:

count1=count1+1

for j in string2:

count2=count2+1

if(count1&lt;count2):

print(“Larger string is:”)

Python programming Lab 14 Dept. of CSE, SVEC


print(string2)

elif(count1==count2):

print(“Both strings are equal.”)

else:

print(“Larger string is:”)

print(string1)

10.1.3 INPUT AND OUTPUT

Larger string is:

Good Computer Coding u can perform using python

EXPERIMENT-10.2

10.2.1 OBJECTIVE

Reverse string without using function in Python

10.2.2 PROGRAM:

my_string=("JNTUA")

str=""

for i in my_string:

str=i+str

print("Reversed string:",str)

10.2.3 INPUT AND OUTPUT

Reversed string: AUTNJ

EXPERIMENT-10.3

10.3.1 OBJECTIVE

Python program to calculate length of a String without using len() function

10.3.2 PROGRAM:

# User inputs the string and it gets stored in variable str

str = input("Enter a string:")

Python programming Lab 15 Dept. of CSE, SVEC


# counter variable to count the character in a string

counter = 0

for s in str:

counter = counter+1

print("Length of the input string is:", counter)

10.3.2 INPUT AND OUTPUT

Enter a string:234

Length of the input string is: 3

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

# Declare the variable vowels,

Python programming Lab 16 Dept. of CSE, SVEC


# consonant, digit and special

# characters

vowels = 0

consonant = 0

specialChar = 0

digit = 0

# str.length() function to count

# number of character in given string.

for i in range(0, len(str)):

ch = str[i]

if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') ):

# To handle upper case letters

ch = ch.lower()

if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):

vowels = vowels+1

else:

consonant = consonant+1

elif (ch >= '0' and ch <= '9'):

digit = digit+1

else:

specialChar = specialChar+1

print("Vowels:", vowels)

print("Consonant:", consonant)

print("Digit:", digit)

print("Special Character:", specialChar)

# Driver function.

Python programming Lab 17 Dept. of CSE, SVEC


str = input("ENTER TEXT:")

countCharacterType(str)

11.4 INPUT AND OUTPUT


ENTER TEXT:"PYTHONPROGRAMMING-536"

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:

Rfirst = ip[0 : len(ip)-d]

Rsecond = ip[len(ip)-d : ]

print("Right Rotation : ", (Rsecond + Rfirst))

else:

Lfirst = ip[0 : -1*d]

Lsecond = ip[-1*d :]

print ("Left Rotation : ",(Lsecond+Lfirst))

ip = input('Enter a word')

d=int(input('Enter of positions to rotate'))

rotate(ip,d)

Python programming Lab 18 Dept. of CSE, SVEC


12.3 INPUT AND OUTPUT

Enter a wordPYTHON

Enter of positions to rotate456

Right Rotation : PYTHON


EXPERIMENT-13

13.1 OBJECTIVE

Given rows of text, write it in the form of columns

13.2 PROGRAM

Import pandas as pd

# Define a dictionary containing employee data

data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32],'Address':['Delhi', 'Kanpur',
'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']}

# Convert the dictionary into DataFrame

df = pd.DataFrame(data)

# converting and overwriting values in column

df["Name"]= df["Name"].str.lower()

print(df)

13.3 INPUT AND OUTPUT

Name Age Address Qualification

0 jai 27 Delhi Msc

1 princi 24 Kanpur MA

2 gaurav 22 Allahabad MCA

3 anuj 32 Kannauj Phd

Python programming Lab 19 Dept. of CSE, SVEC


EXPERIMENT-14

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

factor = 2 * math.sqrt(2) / 9801

while True:

num = (factorial(4 * k)) * (1103 + 26390 * k)

den = (factorial(k) * 4) * (396 * (4 * k))

term = factor * num / den

Python programming Lab 20 Dept. of CSE, SVEC


total = total + term

if abs(term) < 1e-15:

break

k=k+1

return 1 / total

print("Result = ",estimate_pi())

print("Pi = ",math.pi)

14.3 INPUT & OUTPUT:

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

fname = input("Enter file name : ")

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

Python programming Lab 21 Dept. of CSE, SVEC


if count != 0:

print("Occurence of letter ",alphas[i]," is ",count)

15.3 INPUT AND OUTPUT:

Enter file name : p26.py

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

Python programming Lab 22 Dept. of CSE, SVEC


Occurence of letter w is 2

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

Python programming Lab 23 Dept. of CSE, SVEC


EXPERIMENT-16
16.1 OBJECTIVE
Write a program that reads a file, breaks each line into words, strips whitespace and punctuation
from the words, and converts them to lowercase
16.2PROGRAM
.

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

16.3: INPUT AND OUTPUT

['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'

diff = datetime.datetime.strptime(date1, datetimeFormat) - datetime.datetime.strptime(date2,


datetimeFormat)

#print("Difference:", diff)

print("Days:", diff.days)

Python programming Lab 24 Dept. of CSE, SVEC


17.3INPUT AND OUTPUT
Days: 37

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

from datetime import datetime

s1 = input("Enter the first time in fromat (%H:%M:%S) : ")

s2 = input("Enter the second time in fromat (%H:%M:%S) : ")

FMT = '%H:%M:%S'

diff = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

print("The difference between ",s1," and ",s2," : ",diff)

18.3INPUT AND OUTPUT

Enter the first time in fromat (%H:%M:%S) : 12:30:50

Enter the second time in fromat (%H:%M:%S) : 02:40:55

The difference between 12:30:50 and 02:40:55 : -1 day, 14:10:05

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

Python programming Lab 25 Dept. of CSE, SVEC


self.x=x

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

print("Reflection Point on x Axis is: ",self.Destination.x,self.Destination.y)

L=Location(1,2,3,4)

L.show()

L.reflection()

19.3INPUT AND OUTPUT

Source=(1,2)

Destination=(3,4)

Reflection Point on x Axis is: -3,4

Python programming Lab 26 Dept. of CSE, SVEC


EXPERIMENT-20

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

squares=set([x**2 for x in range(1,10)])

cubes=set([x**3 for x in range(1,10)])

print("SQUARES : ",squares)

print("CUBES : ",cubes)

squares.update(cubes)

print("UPDATE : ", squares)

squares.add(11*11)

squares.add(11*11*11)

print("ADD : ", squares)

print("POP : ", squares.pop())

squares.remove(1331)

print("REMOVE : ",squares)

squares.clear()

print("CLEAR : ",squares)

20.3 INPUT AND OUTPUT

SQUARES : {64, 1, 4, 36, 9, 16, 49, 81, 25}

CUBES : {64, 1, 512, 8, 343, 216, 729, 27, 125}

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

Python programming Lab 27 Dept. of CSE, SVEC


EXPERIMENT-21

21.1 OBJECTIVE

Write a program to sum the series 1/1!+4/2!+27/3!+………….

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

n=int(input("Enter the value of n : "))

s=0.0

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

s=s+(float(i**i)/fact(i))

print("Result :",s)

21.3INPUT AND OUTPUT

Enter the value of n : 45

Result : 3.302525713102e+18

Python programming Lab 28 Dept. of CSE, SVEC


EXPERIMENT-22

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

'''Function returns the sum of values passed to it'''

sum=0

for i in args:

sum+=i

return sum

print(add.__doc__)

print("SUM = ",add(25,30,45,50))

22.3 INPUT AND OUTPUT

Function returns the sum of values passed to it

SUM = 150

EXPERIMENT-23

23.1 OBJECTIVE

Write a python program that greets a person

23.2PROGRAM

def greet(name,mesg):

"""This Function Welcomes the person passed Whose name is passed as a parameter"""

print("Welcome," + name + ". " + mesg)

mesg="Happy Reading.Python is Fun !"

name=input("\n Enter your name : ")

Python programming Lab 29 Dept. of CSE, SVEC


greet(name,mesg)

23.3INPUT AND OUTPUT

Enter your name : RAMAKRISHNA

Welcome,RAMAKRISHNA . Happy Reading.Python is Fun !

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:

print(c,"found in string at index : ",index)

return

else:

pass

index+=1

print(c,"is not present in the string")

str=input("\n Enter a string :")

ch=input("\n Enter the character to be searched : ")

find_ch(str,ch)

24.3 INPUT AND OUTPUT

Enter a string :God is great

Enter the character to be searched : r

r found in string at index : 8

Python programming Lab 30 Dept. of CSE, SVEC


EXPERIMENT-25

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

print("List in lowercase characters is : ",list2)

25.3 INPUT AND OUTPUT

List in lowercase characters is : ['hello', 'welcome', 'to', 'python']

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

List = list(filter(is_positive, num_list))

print("Positive Values List = ",List)

26.3 INPUT AND OUTPUT

Positive Values List = [10, 30, 50, 70, 90]

Python programming Lab 31 Dept. of CSE, SVEC


Python programming Lab 32 Dept. of CSE, SVEC

You might also like