Lab Manual For: Advanced Python Programming Lab (CS311PC)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Lab Manual

for
Advanced Python Programming Lab
(CS311PC)

Academic Year: 2022-2023

II B. TECH I SEMESTER

Department of CSE (Internet of Things)

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

S.No Contents Page No.

1 Vision and Mission of the College and Department 01

2 Program Educational Objectives (PEOs) and 02


Program Outcomes

3 Program Specific Outcomes 03

4 Objectives and Course Outcomes of the lab 03

5 List of Experiments 04

6 COs Mapping with POs and PSOs 05

7 Scheme of Evaluation 06

8 Introduction to Lab 06

9 Lab Programs 07

10 Viva questions 24

11 Reference text books and Web References 24


Vision of the College

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.

Mission of the College

Imparting Quality Technical Education to young Engineers by providing the state-of-the-art


laboratories, quality instructions by qualified and experienced faculty and research facilities to meet
the requirements of stakeholders in real time usage and in training them to excel in competitive
examinations for higher education and employment to interface globally emerging techno-informative
challenges in the growth corridor of techno-excellence.

Vision of the Department

To be an epicenter of excellence in education by offering thrust courses, research and


services for the students and make them to succeed in professional competitive examinations globally
with an attitude of entrepreneurial skills, ethical values and social concern.

Mission of the department

Imparting quality Technical Education to young Computer Engineer by providing them:

M1: Impart quality technical Education with State of-the-art laboratories, Analytical and
Technical Skills with International standards by qualified and experienced faculty

M2: Prepare for competitive examinations for higher studies / Employment

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

Program Outcomes Statement


An ability to apply knowledge of mathematics, science, and engineering and
PO1
knowledge of Fundamental Principles.

PO2 An ability to Identify, formulate and solve engineering problems.

An ability to design a system, component, or process to meet desired needs in


Computer Science and Engineering within realistic constraints such as
PO3
economic, environmental, social, political, ethical, health and safety,
manufacturability and sustainability, Design and Modeling.
An ability to design and conduct experiments, as well as to analyze and
PO4
interpret data,Experimentation & Interpret/Engineering Analysis.
An ability to use the techniques, skills and modern Computer Science and
PO5 Engineeringtools necessary for system design with embedded engineering
practice.
Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal andcultural issues and the consequent responsibilities
relevant to the professional engineering practice.

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.

PO9 An ability to function on multidisciplinary teams.

PO10 An ability to communicate effectively.

Demonstrate knowledge and understanding of the engineering and


PO11 management principles andapply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12 A recognition of the need for, and an ability to engage in life-long learning.

Program Specific Outcomes

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

At the end of the course students should be able to:

1. Manipulate and Analyze dataset.


2. Perform statistical analysis.
3. Effectively visualizing result.
4. Develop the skill of designing Graphical user Interfaces.
5. Develop Database Application.
Course Outcomes

Page 3
COURSEC
COURSE OUTCOMES BTL
CODE
Student will be able to write high quality, maintainable Python  L2

C417.1 programsusing python syntax and semantics and be fluent in the


use of Python flow control and functions.

C417.2 Student will be able to database and GUI applications.


 L4

Student will be able to infer the supported data structures like lists,  L3
C417.3
dictionaries, set and tuples in Pythonand use Regular Expressions.

Use the Numpy and pandas for performing complex numerical  L 4


C417.4
analysis tasks

Student will be able to develop and Produce high quality 2D data


C417.5
visualizations using Matplotlib  L 6

C417.6 Student will show sound knowledge of databases programming in  L 2

Python.

LIST OF EXPERIMENTS

1. Create Regular Expressions that


a) Recognize following strings bit, but, bat, hit, hat or hut
b) Match any pair of words separated by a single space, that is, first and last
names.
c) Match any word and single letter separated by a comma and single space,
as in last name, first initial.
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).
e) Match a street address according to your local format (keep your regex
general enough to match any number of street words, including the type
designation). For example, American street addresses use the format:
1180 Bordeaux Drive. Make your regex flexible enough to support multi-
word street names such as: 3120 De la Cruz Boulevard.

2. Create Regular Expressions that:


a) Extract the complete timestamps from each line.
b) Extract the complete e-mail address from each line.

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.

3. Write a multithread program to create 3 threads where one thread calculates


the factorial and second thread calculates square and third thread calculates
the summation of a list of numbers.

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

5. Write a python script that performs basic operations using MySQL database


and a corresponding Python database adapter.

6. Write a python script that performs basic operations using SQLite Database and
a corresponding Python database adapter

7. Write a program to demonstrate operations in Numpy.


8. Write a python program to demonstrate data indexing, selection and filtering in
Pandas.

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.

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

Mapping of COs with POs and PSOs

Program Outcomes (POs) PSOs


PO PO PO PO PO PO PO PO PO PO1 PO1 PO1 PSO PSO PSO BT
CO
1 2 3 4 5 6 7 8 9 0 1 2 1 2 3 L

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

S. No. Assessment of work Evaluation in Marks

1 Lab observation-day to day work 10


2 Record 5

3 Internal laboratory Test 10

Total Marks 25
External Assessment

S. No. Assessment of work Evaluation in Marks

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:

1. Create Regular Expressions that


a) Recognize following strings bit, but, bat, hit, hat or hut
Program:

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:

bat bit but hat hit hut

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:

Schema: https - Host: www.aceec.ac.in - Path: - Querystring:


Schema: ftp - Host: archives.yahoo.com - Path: - Querystring:
Schema: https - Host: www.usp.br - Path: - Querystring:
Schema: https - Host: www.aceenggacademy.com - Path: -
Querystring:
Schema: http - Host: news.yahoo.com - Path: - Querystring: ?
date=today

e) Match a street address according to your local format (keep your


regex general enough to match any number of street words, including
the type designation). For example, American street addresses use
the format: 1180 Bordeaux Drive. Make your regex flexible enough to
support multi-word street names such as: 3120 De la Cruz Boulevard.

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

2. Create Regular Expressions that:


Consider the following string:
‘’’Mr. Akhil logged in at Mon, 19 Jan 2019 07:50:17 GMT from
[email protected]
Mr. Ankit logged in at Sun, 20 Oct 2020 08:20:27 GMT from
[email protected]
Mr. Ravi logged in at Fri, 10 Aug 2021 02:50:47 GMT from [email protected]
Mr. Younus logged in at Tue, 21 Feb 2007 09:10:17 GMT from [email protected]’’’

Write the program to:

a) Extract the complete timestamps from each line.


Program:
import re
timestamp = re.compile("\w{3}, \d{1,2} \w{3} \d{4} \d{2}:\d{2}:\d{2} \w{3}")
matcher = timestamp.findall(str)
for i in matcher:

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

b) Extract the complete e-mail address from each line.


Program:
import re
emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", str)
for i in emails:
print(i)

Output:
[email protected]
[email protected]
[email protected]
[email protected]

c) Extract only the months from the timestamps.


Program:
import re
timestamp = re.compile("\w{3}, \d{1,2} (\w{3}) (\d{4}) (\d{2}:\d{2}:\d{2}) \w{3}")
matcher = timestamp.findall(str)
for i in matcher:
print(i[0])

Output:
Jan
Oct
Aug
Feb

d) Extract only the years from the timestamps.


Program:
import re
timestamp = re.compile("\w{3}, \d{1,2} (\w{3}) (\d{4}) (\d{2}:\d{2}:\d{2}) \w{3}")
matcher = timestamp.findall(str)
for i in matcher:
print(i[1])

Output:

Page 11
2019
2020
2021
2007

e) Extract only the time (HH:MM:SS) from the timestamps.


Program:
import re
timestamp = re.compile("\w{3}, \d{1,2} (\w{3}) (\d{4}) (\d{2}:\d{2}:\d{2}) \w{3}")
matcher = timestamp.findall(str)
for i in matcher:
print(i[2])

Output:
07:50:17
08:20:27
02:50:47
09:10:17

3. Write a multithread program to create 3 threads where one thread


calculates the factorial and second thread calculates square and third
thread calculates the summation of a list of numbers.

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:

Enter first filename:abc.txt


Enter second filename:abcd.txt
Number of lines in fileabc.txtis 4
Number of lines in file abcd.txt is 5

Page 13
[Output varies as two thread run concurrently]

5. Write a python script that performs basic operations using  MySQL


database and a corresponding Python database adapter.
Program:

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

6. Write a python script that performs basic operations using  SQLite


Database and a corresponding Python database adapter

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

7. Write a program to demonstrate operations in Numpy.

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 02:All arithmetic operates elementwise


a = np.array([1, 2, 3, 4]) #create an array
b = np.ones(4) + 1
print(a - b)
print(a * b)
Output:
[-1. 0. 1. 2.]
[2. 4. 6. 8.]

Example 03:Matrix multiplication


c = np.diag([1, 2, 3, 4])
print(c * c)
print("*****************")
print(c.dot(c))
Output:
[[ 1 0 0 0]
[ 0 4 0 0]
[ 0 0 9 0]
[ 0 0 0 16]]
*****************
[[ 1 0 0 0]
[ 0 4 0 0]
[ 0 0 9 0]
[ 0 0 0 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]

Example 05:Logical Operations


a = np.array([1, 1, 0, 0], dtype=bool)
b = np.array([1, 0, 1, 0], dtype=bool)
print(np.logical_or(a, b))
print(np.logical_and(a, b))
Output:
[ True True True False]
[ True False False False]

Example 06:Transcendental functions


a = np.arange(5)
print(np.sin(a))
print(np.exp(a)) #evaluates e^x for each element in a given input
Output:
[ 0. 0.84147098 0.90929743 0.14112001 -0.7568025]
[ 1. 2.71828183 7.3890561 20.08553692 54.59815003]

Basic Reductions
Example 01:computing sums
x = np.array([1, 2, 3, 4])
print(np.sum(x))
Output:
10

Example 02:sum by rows and by columns


x = np.array([[1, 1], [2, 2]])
print(x.sum(axis=0)) #columns first dimension
print(x.sum(axis=1)) #rows (second dimension)
Output:
[3 3]
[2 4]

Example 03:Other reductions


x = np.array([1, 3, 2])
print(x.min())
print(x.max())
print(x.argmin())# index of minimum element
print(x.argmax())# index of maximum element
Output:
1
3
0
1

Example 04:Logical Operations


print(np.all([True, True, False]))
print(np.any([True, False, False]))
#Note: can be used for array comparisions

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

8. Write a python program to demonstrate data indexing, selection and


filtering in Pandas.

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)

#get dimentions of the table


df.shape #total number of rows and columns #(6,4)

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

print(df.columns) #print columns in a table


Index(['day', 'temperature', 'windspeed', 'event'], dtype='object')

Page 18
#get 2 or more columns
print(df[['day', 'event']])

#print max,min.describe temperature


print(df['temperature'].max())
print(df['temperature'].min())
print(df['temperature'].describe())
35
24

Read and write CSV files

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

concatenate Data Frames


import pandas as pd
india_weather = pd.DataFrame({
"city": ["mumbai","delhi","banglore"],
"temperature": [32,45,30],
"humidity": [80, 60, 78]
})
print(india_weather)

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)

Numerical Indexing (.loc vs iloc)

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

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

from tkinter import *

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:

from tkinter import *


top=Tk()
def go(ev=None):
label.config(text="Go...",font="Helvetica 20 bold",fg="green")
def wait(ev=None):
label.config(text="Wait...",font="Helvetica 20 bold",bg="pink",fg="yellow")
def stop(ev=None):
label.config(text="STOP!!",font="Helvetica 20 bold",bg="red")
label=Label(top,text='')
label.pack()
b1=Button(top,text="Go..",font="Helvetica 10 bold",fg="green",command=go)
b1.pack()
b2=Button(top,text="Wait..",font="Helvetica 10
bold",bg="pink",fg="yellow",command=wait)
b2.pack()
b3=Button(top,text="STOP!!",font="Helvetica 10 bold",fg="red",command=stop)
b3.pack()
top.mainloop()

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?

Reference Text Books:

1. Core Python Programming, Wesley J. Chun, Third Edition, Pearson.


2. Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython by Wes McKinny, O’Reilly
Media.
3. Elegant SciPy: The Art of Scientific Python By Juan Nunez-Iglesias, Stéfan van der Walt, Harriet
Dashnow, O’Reilly Media.
4. A. Lukaszewski, MySQL for Python: Database Access Made Easy, Pact Publisher.

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

You might also like