PythonManual-Mech-III-Sem
PythonManual-Mech-III-Sem
RECORD
of
PYTHON
PROGRAMMING
LAB
Page 1 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
External Examiner
Page 2 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
INDEX
EXCERCISE 2
a) A program to compute distance between two points
3 taking input from the user (Pythagorean Theorem). 8
b) A program on add.py that takes 2 numbers as
4 command line arguments and prints its sum 9
EXCERCISE 3
a) A Program to implement for checking whether
5 thegiven number is a even number or not. 10
b) A program to construct reverse the digits of a given
6 number and add it to the original, If the sum is not a 11
palindrome repeat this procedure.
c) A program using a while loop that asks the user for a
7 number, and prints a countdown from that number to 12
zero.
EXCERCISE 4
a) A program to construct the following pattern, using
anested for loop.
*
**
***
8 **** 13
*****
****
***
**
*
Page 3 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Page 4 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Exercise 1 – Basics
Question:
1 a) A sample Python Script using command prompt, Python Command Line and IDLE
Description:
Interactive Mode:
When commands are read from a tty, the interpreter is
said to be in interactive mode.
In this mode it prompts for the next command with the primary prompt, usually 3 greater
than signs(>>>); for continuation lines it prompts with the secondary prompt, by default 3
dots(…).
The interpreter prints a welcome message stating its version number and a copyright notice
before printing the first prompt:
Page 5 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
(or)
Output:
Page 6 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
Program:
Correction:
a=int(input("Enter a value :"))
b=int(input("Enter b value:"))
c=a*b #corrected indent
print(c)
Output:
Output:
Page 7 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Exercise 2 – Operations
Question:
2a) Write a program to compute distance between two points taking input from the
user(Pythagorean Theorem)
Program:
distance=(((x2-x1)**2)+((y2-y1)**2))**0.5
Output:
Page 8 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
2 b)Write a program add.py that takes 2 numbers as command line arguments and prints its sum
Program:
Output:
Page 9 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
3a)Write a Program for checking whether the given number is a even number or not.
Program:
if a%2==0:
else:
Output:
Page 10 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
3b) A program to construct reverse the digits of a given number and add it to the original, If
the sum is not a palindrome repeat this procedure.
Program:
while(True):
Output:
Page 11 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
3c) Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero
Program:
print(" The countdown of numbers from ", n , " are " ,end= " ")
while n>=0:
n=n-1
Output:
Page 12 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
4a) A program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
*
Program:
for i in range(n+1):
for j in range(i):
print()
for i in range(n):
for j in range(i,n-1):
print()
Output:
Page 13 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
4b) Each new term in the Fibonacci sequence is generated by adding the previous two terms. By
starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
Program:
f1,f2,f3,s=0,1,0,0
while f3<4000000:
f3=f1+f2
f1=f2
f2=f3
if f3%2==0:
s+=f3
Output:
Page 14 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Exercise - 5 Functions
Question:
5a)Find mean, median, mode for the given set of numbers in passed as arguments
Program:
def mean(L1):
m=sum(L1)//len(L1)
return m
def median(L):
n=len(L)
sum=0
L.sort()
if(n%2==0):
sum=L[(n//2)]+L[(n//2)-1]
m=float(sum/2)
else:
m=L[(n)//2]
return m
def mode(L1):
counts={}
for i in L1:
j=L1.count(i)
counts[i]=j
max_count=max(counts.values())
mode_values=[key for key, value in counts.items() if value == max_count]
return mode_values
L1=[6,4,2,1,3,7]
L2=[4,6,3,2,7,8]
L3=[2,5,3,2,3,2,5]
Output:
Page 15 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
5b)Write a function nearly_equal to test whether two strings are nearly equal. Two stringsa and b
are nearly equal when a can be generated by a single mutation on b
Program:
def equal(s1,s2):
cnt=0
if len(s1)==len(s2):
for i in range(len(s1)):
if s1[i]!=s2[i]:
cnt=cnt+1
else:
print("The strings are not nearly equal")
return
if cnt<2:
print("The strings are nearly equal")
else:
print("The strings are not nearly equal")
Output:
Page 16 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
Program:
def fact_rec(n):
if n==0 or n==1:
return 1
else:
return n*fact_rec(n-1)
n=(int(input("Enter Number to find factorial=")))
if n>=0:
print("The factorial of ", n , " is ", fact_rec(n))
else:
print("The factorial is not possible")
Output:
Page 17 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
5d)Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one line.
Program:
import math
lcm = lambda a, b: math.lcm(a, b)
gcd = lambda a, b: abs(a*b)//math.lcm(a, b)
Output:
Page 18 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
6a) A program to count the number of strings where the string length is 2 or more and the first and
last character are same from a given list of strings.
Program:
def match(words):
cnt=0
for w in words:
if len(w)>2 and w[0]==w[-1]:
cnt=cnt+1
return cnt
list = input_string.split()
Output:
Page 19 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
6b) A program to develop unzip a list of tuples into individual lists and convert them into dictionary.
Program:
list_tup=[("rahul",23),("Henry",21),("Akash",16)]
unzipped_list=list(zip(*list_tup))
com_dict=dict(zip(unzipped_list[0],unzipped_list[1]))
Output:
Page 20 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Exercise - 7 – DS continued
Question:
7a)Write a program to count the numbers of characters in the string and store them in a dictionary data
structure
Program:
Output:
Page 21 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
7b)Write a program to use split and join methods in the string and trace a birthday with a dictionary
data structure.
Program:
Output:
Page 22 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Exercise - 8 – Modules
Question:
Page 23 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Page 24 of 29
Sri Vasavi Engineering College, Tadepalligudem
Question:
8b)Write a script that imports requests and fetch content from the page. Eg. (Wiki)
Installing Wikipedia:
Step1:download Wikipedia 1.4.0 from https://pypi.python.org/pypi/wikipedia
Step2:place the Wikipedia module in python311/lib folder
Step3:install the Wikipedia module as follows:
Open command prompt
Type c:/python311
Type pip install Wikipedia
Step4:type program as with the filename as wikiex.py
Wikiex.py
import wikipedia
print (wikipedia.summary(“wikipedia”))
ny=wikipedia.page(“sri_vasavi_engineering_college”)
print (“title”,ny.title)
print(”url”,ny.url)
print (“content”,ny.content )
print (“links”,ny.links[0])
Output:
Page 25 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
8c)Write a simple script that serves a simple HTTP Response and a simple HTML Page
Program:
Server.py:
client.py:
import httplib
import sys
http_server=sys.argv[1]
conn = httplib.HTTPConnection(http_server)
Page 26 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
while 1:
cmd = raw_input('input command (ex. GET index.html): ')
cmd = cmd.split()
if cmd[0] == 'exit':
break
conn.request(cmd[0], cmd[1])
rsp = conn.getresponse()
print(rsp.status, rsp.reason)
data_received = rsp.read()
print(data_received)
conn.close()
vasavi.html
<html>
<head>
<title>ECE ROCKS</title>
</head>
<body>
<h1>sri vasavi engineering college</h1>
<h2>pedatadepalli</h2>
<h3>tadepalligudem</h3>
</body>
<html>
Page 27 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Excerise -9 Files
Question:
9a)Write a program to count frequency of characters in a given file. You can use character
frequency to tell whether the given file is a Python program file, C program file or a text file?
Program:
fname = input("Enter file name: ")
f = open(fname, 'r')
s = f.read()
d = {x: s.count(x) for x in set(s) if x not in [' ', '\n']}
if fname.endswith(".py"):
print("It is a Python file.")
elif fname.endswith(".c"):
print("It is a C file.")
elif fname.endswith(".txt"):
print("It is a text file.")
else:
print("It is a file other than Python, C, or text.")
f.close()
Output:
Page 28 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab
Question:
9b)Write a program to compute the number of characters, words and lines in a file.
Program:
filename = "student.txt"
try:
with open(filename, "r") as myfile:
numchars = 0
numlines = 0
numwords = 0
except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output
Page 29 of 29