Lab Manual For: Advanced Python Programming Lab (CS311PC)
Lab Manual For: Advanced Python Programming Lab (CS311PC)
Lab Manual For: Advanced Python Programming Lab (CS311PC)
for
Advanced Python Programming Lab
(CS311PC)
II B. TECH I SEMESTER
ACE
Engineering College
An Autonomous Institution
Ghatkesar, Hyderabad - 501 301, Telangana.
Approved by AICTE & Affiliated to JNTUH
NBA Accredited B.Tech Courses, Accorded NACC A-Grade with 3.20 CGPA
INDEX
5 List of Experiments 04
7 Scheme of Evaluation 06
8 Introduction to Lab 06
9 Lab Programs 07
10 Viva questions 24
To be a leading Technical Institute to prepare high quality Engineers to cater the needs of the
stakeholders in the field of Engineering and Technology with global competence fundamental
comprehensive analytical skills, critical reasoning, research aptitude, entrepreneur skills, ethical values
and social concern.
M1: Impart quality technical Education with State of-the-art laboratories, Analytical and
Technical Skills with International standards by qualified and experienced faculty
M3: Develop professional attitude, Research aptitude, Critical Reasoning and technical
consultancy by providing training in cutting edge technologies.
M4: Endorse and Nurture knowledge, Life-long learning, Entrepreneurial practices, ethical values
and social concern
Page 1
Program Educational Objectives (PEOs)
PEO 1: To prepare the students for successful careers in Computer Science and Engineering and fulfill
the need by providing training to excel in competitive examinations for higher education and
employment.
PEO 2: To provide students a broad-based curriculum with a firm foundation in Computer Science and
Engineering, Applied Mathematics &Sciences.To impart high quality technical skills for
designing, modeling, analyzing and critical problem solving with global competence.
PEO 3: To inculcate professional, social, ethical, effective communication skills and entrepreneurial
practice among their holistic growth.
PEO 4: To provide Computer Science and Engineering students with an academic environment and
membersassociated with student related to professional bodies for multi-disciplinary approach
and forlifelong learning.
PEO 5: To develop research aptitude among the students in order to carry out research in cutting
edgetechnologies, solve real world problems and provide technical consultancy services.
Program Outcomes
Page 2
The broad education necessary to understand the impact of engineering
PO7
solutions in a global, economic, environmental, and societal context.
PO8 An understanding of professional and ethical responsibility.
Program Specific
Statement
Outcomes
To prepare the students ready for industry usage by providing required
PSO1
training in cutting edgetechnologies.
An Ability to use the core concepts of computing and optimization
PSO2
techniques to develop moreefficient and effective computing mechanisms.
Prepare the graduates to demonstrate a sense of societal and ethical
PSO3 responsibility In their professional endeavors and will remain informed
and involved as full participants in the profession and our society.
Course Objectives
Page 3
COURSEC
COURSE OUTCOMES BTL
CODE
Student will be able to write high quality, maintainable Python L2
Student will be able to infer the supported data structures like lists, L3
C417.3
dictionaries, set and tuples in Pythonand use Regular Expressions.
Python.
LIST OF EXPERIMENTS
Page 4
c) Extract only the months from the timestamps.
d) Extract only the years from the timestamps.
e) Extract only the time (HH:MM:SS) from the timestamps.
4. Write a python program to create two threads to count how many lines in two
text files (one thread will count lines from first file and other thread from second
file).
6. Write a python script that performs basic operations using SQLite Database and
a corresponding Python database adapter
9. Write a python program to create GUI application to illustrate slider tool that
controls the size of the text font in the label widget.(Greater the slider position,
larger the font and vice-versa)
10. Write a python program to create GUI application to implement road signs
with the appropriate foreground and background colors based on sign type stop,
wait and Go signal.
Page 5
C417.1 3 3 2 3 2 3 3 3 3 3 2
C417.2 3 2 2 3 2 3 3 3 4
C417.3 2 2 3 3 2 2 2 2 3 3 3 3
C417.4 2 3 3 3 3 2 3 3 3 4
C417.5 3 3 2 3 1 2 1 2 2 2 2 3 3 3 6
C417.6 3 3 3 3 3 2 3 3 2 2 3 2 3 3 3 2
Python
Programmin 2.5 2.8 2.8 2.8 2.5 2.0 2.5 2.0 2.0 2.0 2.7 2.2 3.0 3.0 3.0
g Lab
Scheme of Evaluation
Internal Assessment
Total Marks 25
External Assessment
1 Write up 25
2 Experimentation 25
3 Viva 25
Total Marks 75
Introduction to Lab
Page 6
This lab is all about the programming language Python. In this lab, you are going to try out some
new ideas in this new programming language. Python is an interpreted, object-oriented, high-level
programming language with dynamic semantics. Its high-level built in data structures, combined with
dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as
well as for use as a scripting or glue language to connect existing components together. Python's
simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program modularity and
code reuse. The Python interpreter and the extensive standard library are available in source or binary
form without charge for all major platforms, and can be freely distributed.
In this lab, you are going to teach yourself Advanced Python by solving programming problems
from the topics like python data structures, files, creating multi threaded applications, numpy, pandas,
GUI applications and data base programming using python.
Lab Programs:
import re
words = """bat fish bit book keyboard but nose eye building hat try ok
address hit ten lol hut"""
pattern = re.compile("[bhaiu]{2}t")
result = pattern.findall(words)
print(" ".join(result))
Output:
b) Match any pair of words separated by a single space, that is, first and
last names.
Program:
import re
names = """
Prof K Jayabharathi
Dr G Sreenivasulu
Dr P VenkateswaraRao
Dr P Chiranjeevi
"""
def get_complete_name(name):
complete_name = name.split(" ")
return "First: %s - Last: %s" % (complete_name[0], complete_name[1])
Page 7
pattern = re.compile("[a-zA-Z]+\s[a-zA-Z]+\n")
result = map(lambda x: get_complete_name(x), pattern.findall(names))
print("******************")
print("* NAMES *")
print("******************")
print("\r".join(result))
Output:
******************
* NAMES *
******************
First: K - Last: Jayabharathi
First: G - Last: Sreenivasulu
First: P - Last: VenkateswaraRao
First: P - Last: Chiranjeevi
c) Match any word and single letter separated by a comma and single
space, as in last name, first initial.
Program:
import re
def get_complete_name(name):
return "First: %s - Last: %s" % (name[1], name[0])
names = """
Prof K, Jayabharathi
Dr G, Sreenivasulu
Dr P, VenkateswaraRao
Dr P, Chiranjeevi
"""
pattern = re.compile("([a-zA-Z]+),\s+([a-zA-Z]+)")
print("******************")
print("* NAMES *")
print("******************")
result = map(lambda name: get_complete_name(name),
pattern.findall(names))
print("\r\n".join(result))
Output:
******************
* NAMES *
******************
First: Jayabharathi - Last: K
First: Sreenivasulu - Last: G
First: VenkateswaraRao - Last: P
First: Chiranjeevi - Last: P
Page 8
d) Match simple Web domain names that begin with www. and end with
a “.com” suffix; for example, www.yahoo.com. Extra Credit: If your
regex also supports other high-level domain names, such
as .edu, .net, etc. (for example, www.foothill.edu).
Program:
urls = """
https://www.aceec.ac.in
ftp://archives.yahoo.com
https://www.usp.br
https://www.aceenggacademy.com
http://news.yahoo.com?date=today
"""
import re
def get_url_pattern(url):
return "Schema: %s - Host: %s - Path: %s - Querystring: %s" % (url[0],
url[1], url[2], url[3])
pattern = re.compile("(ftp|http|https)://([\w\.]+)([\w\/]+)?([\?\w\/\=]
+)?")
result = map(lambda uri: get_url_pattern(uri), pattern.findall(urls))
print("\r\n".join(result))
Output:
Program:
import re
def get_complete_address(data):
return "\r\nAddress: %s - Number: %s - City: %s - State: %s" %
(data[0], data[1], data[2], data[3])
addresses = """
Page 9
ACE Engineering College, 999 - Ankushapur - Hy
ACE Academy, 8266 - Abids - TS
"""
pattern = re.compile("([\w\s]+),\s{1}([0-9]+)\s-\s([\w\s]+)\s-\s([a-zA-Z]
{2})")
result = map(lambda address: get_complete_address(address),
pattern.findall(addresses))
print("******************")
print("* ADDRESSES *")
print("******************")
print("\r\n".join(result))
Output:
******************
* ADDRESSES *
******************
Address:
ACE Engineering College - Number: 999 - City: Ankushapur -
State: Hy
Address:
ACE Academy - Number: 8266 - City: Abids - State: TS
Page 10
print(i)
Output:
Mon, 19 Jan 2019 07:50:17 GMT
Sun, 20 Oct 2020 08:20:27 GMT
Fri, 10 Aug 2021 02:50:47 GMT
Tue, 21 Feb 2007 09:10:17 GMT
Output:
[email protected]
[email protected]
[email protected]
[email protected]
Output:
Jan
Oct
Aug
Feb
Output:
Page 11
2019
2020
2021
2007
Output:
07:50:17
08:20:27
02:50:47
09:10:17
Program:
import threading
def cal_sqre(*num):
for n in num:
print(' Square is : ', n * n)
def cal_fact(*num):
for n in num:
fact=1
for i in range(1,n+1):
fact=fact*i
print("factorial of",n,"=",fact)
arr=eval(input("Enter numbers"))
t1 = threading.Thread( target = cal_sqre, args =arr)
t2 = threading.Thread( target = cal_fact, args =arr)
t1.start()
t2.start()
t1.join()
t2.join()
Page 12
Output:Enter numbers(2,4,6,8)
Square is : 4
Square is : 16
Square is : 36
Square is : 64
factorial of 2 = 2
factorial of 4 = 24
factorial of 6 = 720
factorial of 8 = 40320
4. Write a python program to create two threads to count how many lines in
two text files (one thread will count lines from first file and other thread
from second file).
Program:
import threading
first=input("Enter first filename:")
sec=input("Enter second filename:")
def readfile(fil):
f = open(fil,"r")
Content = f.readlines()
print("Number of lines in file",fil,"is",len(Content))
t1 = threading.Thread( target = readfile, args =(first,))
t2 = threading.Thread( target = readfile, args =(sec,))
t1.start()
t2.start()
t1.join()
t2.join()
Output:
Page 13
[Output varies as two thread run concurrently]
import MySQLdb
cn = MySQLdb.connect(user='root')
cn.query('CREATE DATABASE test') #Creating database
cn = MySQLdb.connect(db='test') #Selecting database
cur = cn.cursor() #Creating cursor object
cur.execute('CREATE TABLE users(login VARCHAR(8), uid INT)') #Create table
# Next we will insert a few rows into the database
cur.execute("INSERT INTO users VALUES('Arun', 7000)")
cur.execute("INSERT INTO users VALUES('Arjun', 7001)")
cur.execute("INSERT INTO users VALUES('Aditya', 7200)")
cur.execute("SELECT * FROM users")
for data in cur.fetchall():
print('%s\t%s' % data)
'''Arun 7000
Arjun 7001
Aditya 7200'''
cur.execute("UPDATE users SET login='Arjuna2' WHERE uid=7001")
cur.execute("SELECT * FROM users")
for data in cur.fetchall():
print('%s\t%s' % data)
'''Arun 7000
Arjuna2 7001
Aditya 7200'''
cur.execute('DELETE FROM users WHERE login="Arjuna2"')
cur.execute('DROP TABLE users')
cur.close()
cn.commit()
cn.close()
Program:
import sqlite3
cn = sqlite3.connect('sqlite_test/test')
cur = cn.cursor()
cur.execute('CREATE TABLE users(login VARCHAR(8), uid INTEGER)')
cur.execute('INSERT INTO users VALUES("Arun", 100)')
cur.execute('INSERT INTO users VALUES("Arjun", 110)')
cur.execute('SELECT * FROM users')
Page 14
for eachUser in cur.fetchall():
print(eachUser)
cur.execute('DROP TABLE users')
cur.close()
cn.commit()
cn.close()
Elementwise Operations
Example 01:Basic Operations
import numpy as np
a = np.array([1, 2, 3, 4]) #create an array
print(a + 1)
print(a ** 2)
Output:
array([2, 3, 4, 5])
array([ 1, 4, 9, 16])
Example 04:comparisions
a = np.array([1, 2, 3, 4])
b = np.array([5, 2, 2, 4])
print(a == b)
print(a > b)
Output:
Page 15
[False True False True]
[False False True False]
Basic Reductions
Example 01:computing sums
x = np.array([1, 2, 3, 4])
print(np.sum(x))
Output:
10
Page 16
a = np.zeros((50, 50))
print(np.any(a != 0))
print(np.all(a == a))
a = np.array([1, 2, 3, 2])
b = np.array([2, 2, 3, 2])
c = np.array([6, 4, 4, 5])
print(((a <= b) & (b <= c)).all())
Output:
False
True
False
True
True
Example 05:Statistics
x = np.array([1, 2, 3, 1])
y = np.array([[1, 2, 3], [5, 6, 1]])
print(x.mean())
print(np.median(x))
print(np.median(y, axis=-1)) # last axis
print(x.std() ) # full population standard dev.
Output:
1.75
1.5
[2. 5.]
0.82915619758885
Creating dataframe:
import pandas as pd
df = pd.read_csv("weather_data.csv") #read weather.csv data
print(df)
#list of tuples
weather_data = [('1/1/2017', 32, 6, 'Rain'),
('1/2/2017', 35, 7, 'Sunny'),
('1/3/2017', 28, 2, 'Snow'),
('1/4/2017', 24, 7, 'Snow'),
Page 17
('1/5/2017', 32, 4, 'Rain'),
('1/6/2017', 31, 2, 'Sunny')
]
df = pd.DataFrame(weather_data, columns=['day', 'temperature', 'windspeed', 'event'])
print(df)
#if you want to see initial some rows then use head command (default 5 rows)
print(df.head())
#if you want to see last few rows then use tail command (default last 5 rows will print)
print(df.tail())
#slicing
print(df[2:5])
Page 18
#get 2 or more columns
print(df[['day', 'event']])
import pandas as pd
df = pd.read_csv('weather_data.csv')
print(df)
GROUP-BY
import pandas as pd
df = pd.read_csv('weather_data_cities.csv')
print(df) #weather by cities
Page 19
df = pd.concat([india_weather, us_weather],axis=1)
print(df)
Merge DataFrames
temperature_df = pd.DataFrame({
"city": ["mumbai","delhi","banglore", 'hyderabad'],
"temperature": [32,45,30,40]})
print(temperature_df)
import pandas as pd
import numpy as np
df = pd.DataFrame([1,2,3,4,5,6,7,8,9,19], index=[49,48,47,46,45, 1, 2, 3, 4, 5])
print(s.iloc[:2])
Page 20
def resize(ev=None):
label.config(font="Helvetica -%d bold"%scale.get())
top=Tk()
top.geometry('250x100')
label=Label(top,text="Hello World!",font="Helvetica 10 bold")
label.pack()
scale=Scale(top,from_=40,to=100,orient=HORIZONTAL,command=resize)
scale.pack()
top.mainloop
Output:
10. Write a python program to create GUI application to implement road signs
with the appropriate foreground and background colors based on sign type
stop, wait and Go signal.
Program:
Output:
Page 21
11. Write a python program to create a "Comments" or "Feedback" page for a
Web site. Take user feedback via a form, process the data in your script,
and return a "thank you" screen.
Program:
Index.html
<!doctype html>
<html>
<body>
<h2>Feedback Form</h2><hr/>
<form action = "http://127.0.0.1/feedback.py" >
Message:<textarea name="f" rows=4 cols="10">
Type message here...
</textarea><br/>
<input type="submit" value="send">
</form>
</body>
</html>
Feedback.py
#!/usr/bin/python
import cgi
Page 22
form = cgi.FieldStorage()
msg=form.getvalue('f')
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h2>Thank you for suggestion</h2><hr/>")
print("You message :",msg)
print("</body></html>")
12. Create a CGI application that not only saves files to the server's disk, but
also displays the content of file back to the client.
Program:
Index.html
<!doctype html>
<html>
<body>
<form enctype = "multipart/form-data" action = "http://127.0.0.1/fup.py"
method = "post">
File:<input type=”file” name=”myfile”><br/>
<input type=”submit” value=”upload”>
</form>
</body>
</html>
Fup.py
#!/usr/bin/python
Page 23
import cgi, os
form = cgi.FieldStorage()
fileitem = form['myfile']
if fileitem.filename:
fn = os.path.basename(fileitem.filename)
open('/var/www/' + fn, 'wb').write(fileitem.file.read())
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h2>File Uploaded successfully...</h2><hr/>")
f=open(fn,'r')
data=f.read()
print("Content Uploaded is:",data)
print("</body></html>")
VIVA Questions:
1. Explain about Label, Button and Scale widget in tkinter?
2. How do we create Scale widget which controls the size of the text font in the Label widget?
3. Tell something about multithreading and its advantages?
4. How we create multi threaded application where three thread runs simultaneously?
5. Explain About python DB-API and different DB module parameter styles?
6. Explain about ORM?
7. What are mutable and immutable types in python?
8. How to import module?
9. What are special symbols and character classes in Regular Expression
10. Tell differences between process and threads
11. How to create a web server
12. Why NumPy is used in Python?
13. how to create 3D Array or ND Array ?
14. how to use shape for 3d or Nd Array ?
15. how to create an array of 20 linearly spaced point between 0 to 1?
Page 24
16. Define Series in Pandas?
17. Define DataFrame in Pandas?
18. Define the different ways a DataFrame can be created in pandas?
19. How to get the minimum, 25th percentile, median, 75th, and max of a numeric series?
20. Define GroupBy in Pandas?
Web References:
1. https://www.python.org/
2. https://www.pythonforbeginners.com/basics/python-websites-tutorials
3. https://realpython.com/python-application-layouts/
4. https://www.udemy.com/course/python-the-complete-python-developer-course/
Page 25