0% found this document useful (0 votes)
4 views29 pages

PythonManual-Mech-III-Sem

Python imp exam syllabus topics

Uploaded by

23a81a0372
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views29 pages

PythonManual-Mech-III-Sem

Python imp exam syllabus topics

Uploaded by

23a81a0372
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

RECORD
of
PYTHON
PROGRAMMING
LAB

Page 1 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

SRI VASAVI ENGINEERING COLLEGE


(AUTONOMOUS)
PEDATADEPALLI, TADEPALLIGUDEM.

This is to certify that this is a bonafide record of Practical Work

done in Python Programming Lab by Mr./Ms

bearing Roll No. Of Mechanical Engineering

Branch of III Semester during the academic year 2024 - 2025.

No. of Experiments Done: 22

Faculty In charge Head of the Department

External Examiner

Page 2 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

INDEX

S.No. Date Name of The Experiment Page No Remarks


EXCERCISE 1
a) A sample Python Script using command prompt,
1 Python Command Line and IDLE 5-6
b) A program to purposefully raise an Indentation Error
2 and correct it 7

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

b) By considering the terms in the Fibonacci sequence


9 14
whose values do not exceed four million, find the sum
ofthe even-valued terms
EXCERCISE 5
a) Find mean, median, mode for the given set of numbers
10 passed as arguments to a function 15
b) Develop a function nearly_equal to test whether two
strings are nearly equal. Two strings a and b are nearly
equal when a can be generated by a single mutation on b
11 16

Page 3 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

c) Develop a Recursive Function to find the Factorial of


12 a given number. 17

d) Develop function to compute GCD, LCM of two


13 18
numbers.Each function shouldn’t exceed one line.
EXCERCISE 6

a) A program to count the number of strings where


14 thestring length is 2 or more and the first and last 19
character are same from a given list of strings.
b) A program to develop unzip a list of tuples
15 intoindividual lists and convert them into 20
dictionary.
EXCERCISE 7
a)A program to count the numbers of characters in the
16 21
string and store them in a dictionary data structure
b) A program to use split and join methods in the string
17 22
and trace a birthday with a dictionary data structure.
EXCERCISE 8
a) Install packages requests, flask and explore them
18 23 - 24
using (pip)
b) A program to implement a script that imports requests
19 25
and fetch content from the page. Eg. (Wiki)
c) Develop a simple script that serves a simple HTTP
20 26 - 27
Response and a simple HTML Page
EXCERCISE 9
a) A program to count frequency of characters in a
givenfile. Can you use character frequency to tell
21 28
whether the given file is a Python program file, C
program file or atext file?
b) A program to compute the number of characters,
22 29
words and lines in a file.

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:

Running python programs using interactive mode:


Step-1: Click on start-> All programs->python3.11->IDLE (python GUI).
Step-2: Type the sample code in IDLE as follows:

Page 5 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

(or)

Step-1: Click on start-> All programs->python3.11->IDLE.


Step-2: Click on file menu, click on New file.
Step-3: Type the following code
a=10
b=20
c=a+b
print(c)
Step-4: Save this file (c:\python3.11\addex.py)
Step-5:Press F5 (to run the program).

Running python programs using command prompt

Step-1: Open the notepad editor.


Step-2: Type the following code
a=10
b=20
c=a+b
print(c)
Step-3: Save the file with .py extension (ex: d:\vasavi\addex.py).
Step-4: Open the command prompt (start->Run->cmd).
Step-5: Go to your folder location where you want to save the python program(ex:d:\vasavi).
Step-6: Type the following command for execution python addex.py

Output:

Page 6 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Question:

1b)Write a program to purposefully raise Indentation Error and Correct it

Program:

a=int(input("Enter a value: " ))


b=int(input(“Enter b value: " ))
c=a*b #unexpected indent
print(c)
Output:

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:

x1=int(input(" Enter value to x1: "))

x2=int(input(" Enter value to x2: "))

y1=int(input(" Enter value to y1: "))

y2=int(input(" Enter value to y2: "))

distance=(((x2-x1)**2)+((y2-y1)**2))**0.5

print("The distance between ", (x1,y1) , (x2,y2) , " is " ,distance)

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:

a=int(input("Enter Number 1 "))

b=int(input("Enter Number 2 "))

print("The Sum of two numbers is " ,a+b)

Output:

Page 9 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Exercise - 3 Control Flow

Question:

3a)Write a Program for checking whether the given number is a even number or not.

Program:

a=int(input(" Enter your value = "))

if a%2==0:

print(a ," is even number")

else:

print(a, " is odd number")

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

n=int(input('Enter a number '))


n=str(n)
n1=n[::-1]
s=0
while n!=n1:
n1=int(n)+int(n1)
n1=str(n1)
n=n1[::-1]
s+=1
else:
print(n1,'is palindrome after',s,'steps')

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:

n=int(input("Enter value to n: "))

print(" The countdown of numbers from ", n , " are " ,end= " ")

while n>=0:

print (n , end=" ")

n=n-1

Output:

Page 12 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Exercise 4 - Control Flow – Continued

Question:
4a) A program to construct the following pattern, using a nested for loop.

*
**
***
****
*****
****
***
**
*

Program:

n=int(input("Enter no of rows = "))

for i in range(n+1):

for j in range(i):

print(" * " , end=" ")

print()

for i in range(n):

for j in range(i,n-1):

print(" * " , end=" ")

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

print(f"Sum of even valued terms={s}")

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]

print("The mean of ",L1," is ",mean(L1))


print("The median of ",L2,"is" ,median(L2))
print("The mode of ",L3,"is" ,mode(L3))

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

s1=input("Enter First string =")


s2=input("Enter Second String =")
equal(s1,s2)

Output:

Page 16 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Question:

5c) Develop a Recursive Function to find the Factorial of a given number.

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)

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

print(f"GCD of {num1} and {num2} is: {gcd(num1, num2)}")


print(f"LCM of {num1} and {num2} is: {lcm(num1, num2)}")

Output:

Page 18 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Exercise - 6 Structured Data Type


Question:

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

input_string = input("Enter a list words separated by space ")

list = input_string.split()

print("The words matched are :",match(list))

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

print("The Original list of tuples is ",list_tup)

unzipped_list=list(zip(*list_tup))

print("The unzipped list are ",unzipped_list)

com_dict=dict(zip(unzipped_list[0],unzipped_list[1]))

print("The lists zipped in to dictionary as :",com_dict)

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:

s=input("enter the string ")


no_char=0
for x in s :
no_char+=1
d=dict([(s,no_char)])
print ("the number of characters in the given string",no_char)
print( d)

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:

from collections import Counter


birthdays={"surekha":"6/22/1999","divya":"10/13/1999","sushma":"9/17/1998","prasanna":"03/4/1999"}
num_to_string = {1: "January",2: "February",3: "March",4: "April",5: "May",6: "June",7: "July",
8: "August",9: "September",10: "October",11: "November",12: "December"}
months = []
mn=","
for name, birthday_string in birthdays.items():
month = int(birthday_string.split("/")[0])
months.append(num_to_string[month])
print(Counter(months))
Print(mn.join(Counter(months)))

Output:

Page 22 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Exercise - 8 – Modules
Question:

8a)Install packages requests,flask and explore them using pip


Pip:
 Pip is a package management system(tool) used to install and manage software packages
written in python
 Many packages can be found in the python package index(pyPI)
 Python 2.7.9 and late(on the python series) and python 3.4 and later include pip(pip3 for
puthon3) by default
 One major advantage of pip is the ease of its command-line interface which makes
installing pip software packages as easy as issuing one command
Pip install some-package-name
Users can also easily remove the package
Pip uninstall some-package-name
Downloading and installing pip:
Step-1:goto https://pip.pypa.io/en/stable/installing/
Step2:click on get-pip.py
Step3:save it on desktop with same name
Step4:double click on get-pip.py on your desktop
Step5:goto command prompt
Step6:type the following command for pip installed or not
pip
To install requests package
pip install requests
To install flask package
pip install flask
Output:
Install pip requests package

Page 23 of 29
Sri Vasavi Engineering College, Tadepalligudem Python Programming Lab

Install flask package

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:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


import os
class KodeFunHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
rootdir = 'c:/xampp/htdocs/'
try:
if self.path.endswith('.html'):
f = open(rootdir + self.path)
self.send_response(200)
self.send_header('Content-type','text-html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404, 'file not found')
def run():
print('http server is starting...')
server_address = ('127.0.0.1', 80)
httpd = HTTPServer(server_address, KodeFunHTTPRequestHandler)
print('http server is running...')
httpd.serve_forever()
if name == ' main ':
run()

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>

HOW TO RUN SERVER PROGRAM


Step1:open command prompt to start the server
Step2:goto python311(c:/python311)
Step3:type command as follows
Python server.py

HOW TO RUN CLIENT PROGRAM


Step1:open command prompt
Step2:goto python311(c:/python311)
Step3:type the following command to execute the client programPython
client.py 127.0.0.1
Step4:type the following command to display the content
GET vasavi.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']}

print("The frequency of characters are:")


print(d)

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

for line in myfile:


numchars += len(line)
numlines += 1
wordslist = line.split(" ")
numwords += len(wordslist)

print("Total number of characters:", numchars)


print("Total number of lines:", numlines)
print("Total number of words:", numwords)

except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output

Page 29 of 29

You might also like