List Tuple

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

BE/B.

TECH Degree Examination October 2018


14ITO03 – Python Programming
Seventh Semester
Answer Key
1) s = "Keep learning daily!"
print(s[5:14])

2)
List Tuple
Mutable data type Immutable data type
An ordered group of sequences enclosed by [ ] An ordered group of sequences enclosed by ()
L=[1,2,3] L=(1,2,3)
Sequences can be modified after creation Sequences cannot be modified after creation
Operations like add, delete and update can be Operations like add, delete and update cannot
performed be performed
3)
import datetime
t = datetime.datetime.now()
print ("Current date and time : ")
print (t.strftime("%Y-%m-%d %H:%M:%S"))

4) Decorators are callable objects which are used to modify functions or classes. It accepts some
arguments and returns some objects.
Functions can be passed as arguments to another function
def fun1(fun2):
print("Hello")
fun2()

def fun2():
print("Hi")

fun1(fun2)
5) Name mangling
The leading double underscore triggers python’s name mangling. This helps to avoid attribute
name collisions in subclasses. Hence, private members could be accessed using class name from
outside of the class.
6)  Overriding is the property of a class to change the implementation of a method provided by
one of its base classes.
 In Python method overriding occurs by simply defining in the child class a method with the
same name of a method in the parent class.
7) f = open("text.txt", "r")
s = f.read()
for i in reversed(s):
print(i)
8) Copy is to make a copy of the selected file or folder and place the duplicate in another drive or
folder, while move is to move the original files from one place to another location. The move
command deletes the original files, while copy retains them.
9) GET - fetch information from a server, and should not include sensitive data.
GET parameters are attached to a request via a query string at the end of a URL.
POST - to send data to a server, included parameters may be sensitive and these will also require
added protection such as SSL. POST parameters are attached to a request via the request body.

10) from tkinter import *


window = Tk()
lbl = Label(window, text="User name")
lbl.grid(column=0, row=0)
txt = Entry(window,width=10)
txt.grid(column=1, row=0)
lbl = Label(window, text="Password")
lbl.grid(column=0, row=1)
txt = Entry(window,width=10)
txt.grid(column=1, row=1)
btn = Button(window, text="Submit")
btn.grid(column=0, row=3)
window.mainloop()

Part – B (5 x 13 = 65 Marks)
11)a.i) Python Program - Calculate Grade of Student
# Get the details for three assessments - 2M
print("Enter marks sports ");
ass1 = input();
print("Enter marks for three activities");
...
# Assign weight-age 20%, 30% and 50% for ass1, ass2 and ass3 respectively - 1M
average = ass1*.2 + ass2*.3 + ass3*50
# Find the grade – 4M
if(average>=91 and average<=100):
print("Your Grade is A+");
elif(average>=81 and average<=90):
print("Your Grade is A");
...
else:
print("RA");
11 a.ii) c=0;
print("Enter -1 to exit");
num=input("enter a number") 1M
while(num)
{ # prime number checking 4M
for i in range(2,num):
if (num % i) == 0:
break
else:
c=c+1 # counting 1M
num=input("enter a number") # repeat to get input
}
print(c) # print the count value – 1M
11b.i) Set - 2M
 Set contain unique elements only
 Immutable like tuples and strings
 eg. {1,2,3}
11 b. i) Various operations on set – 5M

11.b.ii) squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary


new=squares.copy() - copy the existing to new - 1M
squares[key] - retrieve a particular value using key – 1M

squares[key]=value – insert new key value pair – 1M


# If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
(or)
Squares.update({key,value})

squares.clear() - remove all items - 1M


squares.pop(key) or del squares[key] - delete a particular item – 1M
squares[key]=value - update the value using key – 1M
12 a. User name : Pattern = '^[A-Za-z]$' – 4M
Password : Pattern = ‘^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$’ – 9M
12 b. i)

def printme( str ):


print str
return

printme('kongu engineering')
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
def printinfo( name, age )
print "Name: ", name
print "Age ", age
return
printinfo( age=50, name="babu" )
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
def printinfo( name, age = 35 ):
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="babu" );
printinfo( name="devi" ); # age=35 default arg

Variable-length arguments
You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return
printinfo( 10 )
printinfo( 70, 60, 50 )
12 b.ii)

2M

2M
2M

13 a. class company: # base class - 2M


def __init__(self, name, address):
self.cname=name
def paycal:
...
class salaried(company): # derived class1 - 3M
def __init__(self, eno, ename, basic,da,hra,it,pf):
def paycal:
....
class fixed(company): # derived class2 - 3M
def __init__(self, eno, ename, basic,da,hra,it,pf):
def paycal:
class hourly(company): # derived class3 - 3M
def __init__(self, eno, ename, basic,da,hra,it,pf):
def paycal:
...
ob1=salaried('ABC', ’Erode’, 111,'Gobi',10000,500, 100, 150, 200)
ob.paycal() #object creation and invoking methods -2M

13 b i)  Create a directory 'P1' to create a package of the same name. 1M


 Create a file __init__.py and place it inside directory P1. 1M
 Create sub-directories ‘artithmetic’ and ‘factorial’ and place __init__.py inside each sub-
directory. 2M
 Create the corresponding modules inside each sub-package. 3M

13 b ii) Polymorphism & Duck typing – 2M


 Python’s duck typing, a special case of dynamic typing, uses techniques characteristic of
polymorphism, including late binding and dynamic dispatch.
 Polymorphism is the ability to leverage the same interface for different underlying forms
such as data types or classes. This permits functions to use entities of different types at
different times.
 Polymorphism can be carried out through inheritance, with subclasses making use of base
class methods or overriding them.
Polymorphism example (or any other example) – 4M
The example would be to have an abstract class Car which holds the structure drive () and stop().
We define two objects Sportscar and Truck, both are a form of Car.
14 a.i) #copy the content of the file to another file
#Open one file called test.txt in read mode. -2M
with open("test.txt", "r") as f:
#Open another file out.txt in write mode. -2M
with open("out.txt", "w") as f1:
#Read each line from the input file and writes it into the output file. -3M
for line in f:
f1.write(line)

14a.ii) Directory operation – 6M


(Any six from the following and each carry 1 M)
os.chdir() - to change the current working directory
os.getcwd() - current working directory
os.listdir() - To get the contents of a directory into a python list
os.mkdir()- create a directory
os.rename()- to give new name to the directory
os.rmdir()- to remove the directory
os.path.join() - combine the directories
os.path.split()- splits the directory
os.path.exist()- to check the direcory exist or not

14b.i) Various modules to implement various data base


Python Mysql connection with any of the following three different packages – 3M
MySQL-python
mysql-connector-python
PyMySQL

Python sqlite connection - sqlite3 -1M


Python Oracle connection - cx_Oracle() – 1M

14bii) File I/O for structured file – CSV and JSON – 1M


CSV - Reader and Writer Modules – 4M
csv.reader function
csv.writer function
csv.Dictwriter class
csv.DictReader class
JSON-JavaScript Object Notation- 3M
json.load() – read the JSON data (python to JSON)
json.dumps()- write the JSON data (JSON to python)

15a Chat application using – tcp


# server.py - 8M
import socket # import necessary packages
# create a socket object
serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname() # get host machine name
port = 4567
serversocket.bind((host, port)) # bind to the port
serversocket.listen(5) # Start the tcp listener
while True:
clientsocket.addr = serversocket.accept() # establish a connection
clientsocket.send('Welcome') # send messgage to client
data = clientsocket.recv(1024) # receive the message
print(data)
clientsocket.close() # closes the connection

# client.py - 5M
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create a socket object
host = socket.gethostname() # get local machine name
port = 4567
s.connect((host, port)) # connection to hostname on the port.
tm = s.recv(1024) # Receive no more than 1024 bytes
s.send(“hai”) # send the message
s.close() # closes the connection
print(tm)

15bi) File Upload using CGI


#Client side - 3M
<html>
<body>
<form enctype = "multipart/form-data"
action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>

#Server side – 4M
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open(fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
15bii) Various UDP socket methods
(Any six from the following and each carry 1 M)
# socket creation socket_type=SOCK_DGRAM for UDP
S = socket.socket(socket_family, socket_type, protocol=0)
connect( ) - To connect to a remote socket at an address.
bind( )- binds the socket to an address
listen(backlog)- listens for the connection made to the socket.
The backlog is the maximum number of queued connections
that must be listened before rejecting the connection.
accept( ) -accept a connection.
s.recvfrom()- Receives UDP messages
s.sendto()-Transmits UDP messages
General methods
close() - close the socket connection.
gethostname()- hostname of the machine where the python interpreter is currently executing. .
gethostbyname() - If you want to know the current machine's IP address, you may use
gethostbyname(gethostname()).

16a) import MySQLdb; #import necessary module to establish data base connection – 1 M

# create connection object – 2M


db = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="MySQL", db="db1")
cursor1 = db.cursor() # create cursor object

#create a table -2M


sql = "CREATE TABLE book_details (book_id VARCHAR(20) NOT NULL, …. )"
cursor1.execute(sql) # execute the query

#insert records - 5M
sql = "INSERT INTO book_details (...)"
cursor1.execute(sql)
#str1=input("Enter name")
sql=("INSERT INTO book_details (...))
cursor1.execute(sql)
db.commit()

#update book details -2M


bid=input("enter book id for update")
sql1=update book_details set book_tile="..." where book_id=bid
cursor1.execute(sql1)

# Retrive the book -2M


sqlCommand = "SELECT * FROM book_details where year_publication=100 and
Publisher_name='Pearson Education"
cursor1.execute(sqlCommand)
db.close() # closes the connection - 1M
16 b) Create website for ticket reservation system using CGI
Ticket reservation can be any one (train , bus , air, movie etc)
Design a home page that includes all the operations supported by website – 3M
Availability – 4M
Reservation – 4M
Cancellation – 4M
index.html # Home page
<html>
<body>
<h1> Train Ticket Reservation </h1>
<h2> <a href="Avail.html"> Availability </a>
<a href="Reserve.html"> Reservation </a>
<a href="Cancel.html"> Cancellation </a>
</h2>
</body>
</html>

Design a separate web page for performing a particular operation and corresponding server
program to support the same.
Avail.html # Web page for ticket availability (front end)
<form action = "Avail.py" method = "post">
Source name: <input type = "text" name = "source_name"><br
Destination Name: <input type = "text" name = "destination_name" />
...
<input type = "submit" value = "Submit" />
</form>

Aail.py # server program to support availability operation with back end


import cgi, cgitb # Import modules for CGI handling
import MySQLdb # Import modules for data base connectivity
form = cgi.FieldStorage() # Create instance of FieldStorage
Source_name = form.getvalue('source_name') # Get data from fields
Destination_name = form.getvalue('destination_name')
print "<html>"
print "<head>"
print "<title>Ticket Availability</title>"
print "</head>"
print "<body>"
...
print "</body>"
print "</html>"

You might also like