Solution/Model Answer of VTU exam June 18 is at the end of page(Linked to drive)
Lecture Notes of Dr. P. N. Singh can be accessed/downloaded from drive /uploaded file (See Below of IATs solutions)
Solution/Model Answer
Python Application Programming (15CS664)
IAT-3, 6th Sem CSE
Dr. P. N. Singh, Professor(CSE)
1 a) What do you mean by “orchestrating the movement of data between objects”. Discuss with example code. 5m
Ans:
In OOPs a program is “orchestrating the movement of data between objects”. Back then it was just lines of code that got the job done. It is managing data in motion. It is how we build a network of interacting objects and orchestrate the movement of information between the objects to create a program.
A program as network of objects
#any simple example code for OOPs:
class song:
def gao(self):
print(“Ek pyar ka nagma hai”)
s1=song( )
s2=song( )
s1.gao( )
s2.gao( )
The same lyrics move within objects
1 b) How multiple inheritance can be used in Python programming. Explain with example
program. 5m
Ans:
Python supports a limited form of multiple inheritance as well. A sub-class is derived from more than one base class. A class definition with multiple base classes looks like this:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
……
#multiple inheritance
class horse:
def hsound(self):
print("Neighss....Hin...n.n..")
class ass:
def asound(self):
print("bra....ys.......dhinchu.")
class donkey(horse,ass):
def dsound(self):
print("Neighss....Hin..Braysss... ss...Dhinchu")
d1 = donkey()
d1.hsound()
d1.asound()
d1.dsound()
2. Differentiate data hiding & data encapsulation. Implement data hiding in a OOPs program of Python 10m
Ans:
#data hiding - protection - Example
class JustCounter:
__secretCount = 0 # variable should preceed double underscore
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
# print (counter.__secretCount) error, yes it can't be accessed outside
print (counter._JustCounter__secretCount) # works
3 a) What is a socket? How does http protocol work? Define parameters AF_INET & SOCK_STREAM. 5m
Ans:
Socket: The network protocol that powers the web to make network connections is classed socket. It is built-in feature in python which makes it very easy to make network connections and retrieve data over those sockets in a Python program.
The easiest way to show how the HTTP protocol works is to write a very simple Python program that makes a connection to a web server and follows the rules of the HTTP protocol to request a document and display what the server sends back.
Syntax of get request defined in above document:
GET http://data.pr4e.org/romeo.txt HTTP/1.0
80 is port number of www.py4e.org server
# to calls the socket class from socket library to create a network end point
>>> import socket
>>> mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. The SOCK_STREAM means connection oriented TCP protocol.
3 b) Write a Python program using socket to connect ‘data.pr4e.org’ and to print the contents of ‘romeo.txt’. 5m
Ans:
#socket program example
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data=mysock.recv(20)
if(len(data)<1):
break
print(data.decode(),end='')
4 a) Explain with example to retrieve a web-page with urlib library. 5m
Ans:
While we can manually send and receive data over HTTP using the socket library, there is a much simpler way to perform this common task in Python by using the urllib library.
Using urllib, you can treat a web page much like a file. You simply indicate which web page you would like to retrieve and urllib handles all of the HTTP protocol and header details.
>>> import urllib.request
>>> fhand= urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
>>> for line in fhand:
print(line.decode().strip())
Once the web page has been opened with urllib.urlopen, we can treat it like a file and read through it using a for loop.
When the program runs, we only see the output of the contents of the file. The headers are still sent, but the urllib code consumes the headers and only returns the data to us.
As an example, we can write a program to retrieve the data for romeo.txt and compute the frequency of each word in the file as follows:
>>> import urllib.request, urllib.parse, urllib.error
>>> fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
>>> counts=dict()
>>> for line in fhand:
words=line.decode().split()
for word in words:
counts[word]=counts.get(word,0)+1
>>> print(counts)
4 b) What is ‘scrap the web’ or web scraping? Write with Example code. 5m
Ans:
One of the common uses of the urllib capability in Python is to scrape the web. Web scraping is when we write a program that pretends to be a web browser and retrieves pages, then examines the data in those pages looking for patterns.
>>> import re
>>> url=input('Enter - ')
Enter - http://data.pr4e.org/romeo.txt
>>> html=urllib.request.urlopen(url).read()
>>> links=re.findall(b'A.+',html)
>>> for link in links:
print(link.decode())
5 a) What is the use of XML(eXtensible Markup Language)? Write one sample XML document. 5m
Ans:
There are formats that we use when exchanging data across the web. The “eXtensible Markup Language” or XML has been in use for a very long time and is best suited for exchanging document-style data.
XML(eXtensible Markup Language): XML looks very similar to HTML, but XML is more structured than HTML. Here is a sample of an XML document:
<person>
<name>Singh</name>
<phone type="intl">
+918825168846
</phone>
<email hide="yes"/>
</person>
Often it is helpful to think of an XML document as a tree structure where there is a top tag person and other tags such as phone are drawn as children of their parent nodes.
Here is a simple application that parses some XML and extracts some data elements from the XML:
>>> import xml.etree.ElementTree as ET
>>> data='''
<person>
<name>Singh</name>
<phone type="intl">
+918825168846
</phone>
<email hide="yes"/>
</person> '''
>>> tree=ET.fromstring(data)
>>> print('Name:', tree.find('name').text)
Name: Singh
>>> print('Attr:', tree.find('email').get('hide'))
Attr: yes
>>>
5 b) Often the XML has multiple nodes and we need to write a loop to process all of the nodes.
Write a program to loop through all the user nodes. 5m
Ans:
# In the following program, we loop through all of the user nodes:
import xml.etree.ElementTree as ET
input = '''
<stuff>
<users>
<user x="2">
<id>12504</id>
<name>Singh</name>
</user>
<user x="5">
<id>12505</id>
<name>Rani</name>
</user>
</users>
</stuff>'''
stuff=ET.fromstring(input)
lst=stuff.findall('users/user')
for item in lst:
print('Name',item.find('name').text)
print('Id',item.find('id').text)
print('Attribute',item.get("x"))
6 a) What is JSON or JSON format? Implement parsing the JSON & read through the data in a Python Program. 5m
Ans:
The JSON format was inspired by the object and array format used in the JavaScript language. But since Python was invented before JavaScript, Python’s syntax for dictionaries and lists influenced the syntax of JSON. So the format of JSON is nearly identical to a combination of Python lists and dictionaries.
Parsing JSON: We construct our JSON by nesting dictionaries (objects) and lists as needed. In this example, we represent a list of users where each user is a set of key-value pairs (i.e., a dictionary). So we have a list of dictionaries.
In the following program, we use the built-in json library to parse the JSON and read through the data.
import json
data = '''
[
{ "id" : "001",
"x" : "2",
"name" : "Dr. P. N. Singh"
} ,
{ "id" : "009",
"x" : "7",
"name" : "Dr. Jhansi Rani"
}
]'''
info = json.loads(data)
print('User count:', len(info))
for item in info:
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])
6 b) Define API with diagram? What are 2 advantages of Service Oriented Architecture? 5m
Ans:
Application Programming Interface: “To define document “contracts” between applications”
The general name for these application-to-application contracts is Application Program Interfaces or APIs.
When we begin to build our programs where the functionality of our program includes access to services provided by other programs, we call the approach a Service-Oriented Architecture or SOA. A SOA approach is one where our overall application makes use of the services of other applications. A non-SOA approach is where the application is a single standalone application which contains all of the code necessary to implement the application.
Advantages of SOA:
(1) we always maintain only one copy of data (this is particularly important for things like hotel reservations where we do not want to over-commit) and
(2) the owners of the data can set the rules about the use of their data.
7. Write a program using geocoding API to find out search string from google map and to say about land marks nearby. 5m
Ans:
#Example program/application: geojson.py
import urllib.request, urllib.parse, urllib.error
import json
# Note that Google is increasingly requiring keys
# for this API
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = input('Enter location: ')
if len(address) < 1: break
url = serviceurl + urllib.parse.urlencode(
{'address': address})
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
if not js or 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue
print(json.dumps(js, indent=4))
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print('lat', lat, 'lng', lng)
location = js['results'][0]['formatted_address']
print(location)
8 a) What is a cursor( ) in terms of sqlite? Write an example program to create table student with fields roll, name and marks & insert 3 records into table. 5m
Ans:
A cursor is like a file handle that we can use to perform operations on the data stored in the database. Calling cursor() is very similar conceptually to calling open() when dealing with text files.
Once we have the cursor, we can begin to execute commands on the contents of the database using the execute() method.
#program to create table student
import sqlite3
conn = sqlite3.connect('mydata.db')
cur=conn.cursor()
cur.execute('CREATE TABLE student(roll integer, name text, marks integer)')
cur.execute('insert into student values(111,"Paras",78)')
cur.execute('insert into student values(222,"Kumar",85)')
cur.execute('insert into student values(111,"Amit",67)')
conn.commit()
cur.execute('Select * from students')
for row in cur:
print(row)
8 b) Write a python program using SQL commands in python two join two tables. 5m
Ans:
import sqlite3
conn = sqlite3.connect('friends.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM People')
count = 0
print('People:')
for row in cur:
if count < 5: print(row)
count = count + 1
print(count, 'rows.')
cur.execute('SELECT * FROM Follows')
count = 0
print('Follows:')
for row in cur:
if count < 5: print(row)
count = count + 1
print(count, 'rows.')
cur.execute('''SELECT * FROM Follows JOIN People
ON Follows.to_id = People.id
WHERE Follows.from_id = 2''')
count = 0
print('Connections for id=2:')
for row in cur:
if count < 5: print(row)
count = count + 1
print(count, 'rows.')
cur.close()
Solution/Model answer of IAT-2
Solution/Model Answer
Python Application Programming – 15CS664 – IAT-2
6th Sem CSE ( A, B & C)
Dr. P. N. Singh, Professor(CSE)
1. 1
a. Differentiate array and list in Python. [05]
Ans:
List
• List stores different data types & mostly used in python
• Takes more memory space for variable length of data.
Example:
>>> marks_list = [ [222, 'Rubiya', 67], [333,'Khushboo', 58],[444,'Chinmay', 82]]
>>> for marks in marks_list:
print(marks)
[222, 'Rubiya', 67]
[333, 'Khushboo', 58]
[444, 'Chinmay', 82]
Array
• Array stores values of same type
• We will have to import arrays
• Useful for memory efficiency
from array import *
>>> x=array('i',[3,6,9,12]) # i is typecode
>>> for a in x:
print(a/3)
1.0
2.0
3.0
4.0
>>>x.append(15)
>>>print( x)
array('i', [3, 6, 9, 12, 15])
Some comments over list vs array:
o Python lists are implemented internally as variable-length arrays, rather than linked lists.
· Main difference is the function performed on them
o Since list may have different data types so any operation for all elements like array cannot be performed
b. Differentiate pop() method and del operator in list with examples [05]
Ans:
pop() – deleting elements, if element number is not given then it pops & deletes last element. Popped value can be stored to other variable.
>>> namelist.pop(5)
'paras'
>>> namelist
['Akrur', 'Vinay', 'Vinayak', 'ajay', 'kunti', 'samartha']
>>> namelist.pop()
'samartha'
>>> namelist
['Akrur', 'Vinay', 'Vinayak', 'ajay', 'kunti']
>>> x=namelist.pop(0)
>>> x
'Akrur'
>>> namelist
['Vinay', 'Vinayak', 'ajay', 'kunti']
>>>
del operator deletes the value
(if not required to save to other variable)
>>> del namelist[1]
>>> namelist
['Vinay', 'ajay', 'kunti']
>>>
2. 2
a. Imply split and join in list with examples. [05]
Ans:
split() method
We can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:
>>> gana="dil-mera-lay-gai-Sona-Sona"
>>> gana.split(delimeter)
['dil', 'mera', 'lay', 'gai', 'Sona', 'Sona']
join() method
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter=' '
>>> delimiter.join(t)
'pining for the fjords'
b. Define aliasing & implement with list example. [05]
Ans:
Aliasing: if a refers to an object we assign b = a, then both variables refer to same object. The association of a variable with an object is called a reference. In this example, there are two references to the same object. We say the object is aliased.
>>> nlist3=nlist1
>>> nlist1 is nlist3
True
>>>
If the aliased object is mutable, changes made with one alias affect the other: In general, it is safer to avoid aliasing when you are working with mutable objects.
>>> nlist3[0]=99
>>> nlist1
[99, 3, 4]
So, in case of strings we know that strings are immutable. Aliasing the string object aliasing is not as much of a problem but we can’t change/modify characters of string.
>>> name1[0]='k'
TypeError: 'str' object does not support item assignment
3 3. 3 Write a program Python to pass the list as argument to a function and to return list. [10]
Ans:
Passing list as arguments: When we pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change.
>>> names=['Paras','Kumar','Yash']
>>> def delfirst(strlist):
del strlist[0]
>>> delfirst(names)
>>> names
['Kumar', 'Yash']
# Program to return a list
def delfirstlast(list1):
del list1[0]
del list1[len(list1)-1]
return list1
list2=[1,3,5,7,9]
list3=delfirstlast(list2)
print(list3)
output:
[3, 5, 7]
4
4.
a. Define tuple of python with example of initializing a tuple. ‘Tuples are immutable’: explain with example. [06]
Ans:
A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses to help us quickly identify tuples when we look at Python code:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
Without the comma Python treats (’a’) as an expression with a string in parentheses that evaluates to a string:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
>>> names=('paras','chandan','vikram')
>>> type(names)
<class 'tuple'>
Another way to construct a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
>>> t = tuple()
>>> print(t)
()
b. Write output with justification of following comparison of tuples: [04]
I. (4,2,5) > (4,3,1)
II. (2,2,2) > (2>2>2)
III. (2,2,2,1) > (2>2>2)
IV. ('abc',2,'xyz') < ('xyz',2,'abc')
Ans:
i. >>> (4,2,5) > (4,3,1)
False # 4 equals 4 so second elements 2 > 3 compared & results False.
ii. >>> (2,2,2) > (2>2>2)
True # second expression is false & True > False is True
If second expression is (2,2,2) then False because it has not reached to conclusion.
iii. (2,2,2,1) > (2>2>2)
True # second expression is false & True > False is True
If second expression is (2,2,2) then also it will return True because 4th element of first tuple has nothing to compare with second
iv. ('abc',2,'xyz') < ('xyz',2,'abc')
True # because first expression ‘abc’ is < ‘xyz’
5. 5 How to print keys of dictionary in alphabetical order? Explain with example code in Python. [10]
Ans:
If we want to print the keys in alphabetical order, we first make a list of the keys in the dictionary using the keys method available in dictionary objects, and then sort that list and loop through the sorted list, looking up each key and printing out key-value pairs in sorted order as follows:
>>> marks={'Ricky':45,'Micky':67,'Donald':76,'Janhavi':55,'Yash':88}
>>> for key in marks:
print(key, marks[key])
Ricky 45
Donald 76
Micky 67
Yash 88
Janhavi 55
Now for keys in alphabetical order:
>>> list1=list(marks.keys())
>>> list1.sort()
>>> for key in list1:
print(key,marks[key])
Donald 76
Janhavi 55
Micky 67
Ricky 45
Yash 88
6
6.
a. Differentiate tuple and list with examples. [05]
Ans:
Tuple & List
· A tuple is an (immutable) ordered list of values. It is in many ways similar to a list.
· Most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.
· Tuples have structure, lists have order.
· Tuple occupies smaller size so it becomes a bit faster for big-data range.
· Tuple is immutable so can be used as key in dictionary
Comments:
· If a list is unlikely to be changed, we should use tuples instead of lists.
· Lists are more common than tuples, mostly because they are mutable. But there are a few cases where we may prefer tuples:
o In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. In other contexts, you might prefer a list.
o If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.
o If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.
Example of list:
>>> grade=['a','First',3,2.5]
>>> grade
['a', 'First', 3, 2.5]
>>> type(grade)
<class 'list'>
>>>lst1=[] #empty list
>>>lst1
[]
Example of Tuple:
>>> grade=('a','First',3,2.5)
>>> grade
('a', 'First', 3, 2.5)
>>> type(grade)
<type 'tuple'>
>>>t1=()
>>>t1
()
b. Write a program to open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split function. For each word, check to see if the word is already in a list. If the word is not in the list, add it to the list. When the program completes, sort and print the resulting words in alphabetical order. [05]
Ans:
#sorting unique words of a file
fhand = open('romeo.txt')
allwords=[]
for line in fhand:
words = line.split() #splitting line in words
for word in words:
if word not in allwords:
allwords.append(word) # adding only unique words in list
allwords.sort() # case sensitive on ASCII value
print('\nAll unique words in sorted manner: - ASCII value')
print(allwords)
allwords.sort(key=lambda x:x.lower()) # alphabetical order ignoring the case
print('\nAll unique words in alphabetical order: - ignoring the case')
print(allwords)
7. 7
a. Open file employee.txt and write Python command with regular expression (importing re) for the followings: [06]
i. To print the lines having words “singh” and “sinha”
ii. To print lines having words “agarwal” and “agrawal”
iii. To print the lines ending with “manager”
IV. To print the lines starting with ‘P’
Ans:
>>> open(‘employee.txt’)
>>> import re
i. To print the lines having words “singh” and “sinha”
>>> for line in file1:
if re.search('sin??',line):
print(line)
ii. To print lines having words “agarwal” and “agrawal”
>>>for line in file1:
if re.search('Ag..wal',line): #here . matches any character except a new line
print(line)
iii. To print the lines ending with “manager”
>>> for line in file1:
if re.search('manager$',line):
print(line)
iv. To print the lines starting with ‘P’
>>>for line in file1:
if re.search('^P.*',line): # here . any character and * for 0 or more repeat
print(line)
b. Explain use of \S and [ ] in regular expression. [04]
Ans:
\S represents a non-whitespace character.
Example to find a sub-string look like email address(does not contain white space)
>>> s = 'A message from csev@umich.edu to cwen@iupui.edu about meeting @2PM'
>>> lst=re.findall('\S+@\S+',s)
>>> lst
['csev@umich.edu', 'cwen@iupui.edu’]
[ ] are used to indicate a set of multiple acceptable characters for matching
Example: for substrings that start with a single lowercase letter, uppercase letter, or number “[a-zA-Z0-9]”, followed by zero or more non-blank characters (“\S*”)
Searching for marks 60 to 99 i.e. first digit is 6 to 9 and 2nd digit is 0 to 9
>>> for line in file1:
if re.search('[6-9][0-9]',line):
print(line,end='')
8. 8
a. Define a class employee in python using constructor to initialize empid, name and salary data of instances. Write methods to display employee details and to count number of employees. [05]
Ans:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary): #class constructor for initialization
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount )
def displayEmployee(self):
print( "Name : ", self.name, ", Salary: ", self.salary )
emp1 = Employee("Dr. P. N. Singh", 150000) #created first objects with its data
emp2 = Employee("Dr. A. K. Nayak", 160000) #created first objects with its data
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount )
#executing the program output will be
Name : Dr. P. N. Singh , Salary: 150000
Name : Dr. A. K. Nayak , Salary: 160000
Total Employee 2
b. Define attribute, constructor, destructor, namespace & scope for object oriented programming in python. [05]
Ans:
· Attribute: A variable that is part of a class.
· Constructor: An optional specially named method __init__ () that is called at the moment when a class is being used to construct an object. Usually this is used to set up initial values for the object.
· Destructor: An optional specially named method __del__() that is called at the moment just before an object is destroyed. Destructors are rarely used.
· namespace: A namespace is a mapping from names to objects. Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits.
· Scope: A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
Solution/Model answer of IAT-1
Solution/Model Answer of IAT-1 (March 2018)
Python Application Programming-15CS664 (OE)
VI Sem – CSE
Dr. P. N. Singh, Professor(CSE)
1.
a. What is the function of the secondary memory in a computer? Where in the computer is a variable such as “x” stored after the following Python line finishes?
x = 123 05
Ans:
Examples of secondary memory are disk drives, CDs or flash memory (Pen-drives) used to store information permanently. Secondary memory is much slower than the main memory. The advantage of the secondary memory is that it can store information even when there is no power to the computer.
When value of variable is initialized by the statement:
x=123
Memory management of operating system stores this value occupying the memory cells according to size of data type & that particular region is named as x.
In python decision of data type and their size is dynamic according to initialized data. In above case as the Python finishes, internally data type is declared as of “integer” class. We can check the type.
>>> x=123
>>> type(x)
<class 'int'>
We can check the memory address also by in-built function id( )
>>> id(x)
1550147760
b. Write a Python Program to prompt the user for hours and rate per hour to compute gross pay using try and except so that your program handles invalid type of input by printing a message. The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input 05
Ans:
#Computing pay/wages
rate=input("Enter rate : ")
hours=input("Enter wages : ")
try:
rate=float(rate)
hours=float(hours)
gross_pay=rate*hours
print('Gross Pay = Rs.',gross_pay)
except:
print('Please enter numeric input')
Expected Output:
Enter rate : 82
Enter wages : nine
Please enter numeric input
Again:
Enter rate : 82
Enter wages : 9
Gross Pay = Rs. 738.0
2.
a. Write a Python program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the sum, minimum, maximum and average of the numbers. If the user enters anything other than a number, print an error message and continue the current iteration again. 05
Ans:
#largest and smallest in number
largest=smallest=None
tot=0
kount=1
while True:
num = input("Enter a number (done to end) : ")
if num == 'done':
break
try:
n = int(num)
except:
print ("Invalid input")
continue
if largest == None or largest < n:
largest = n
if smallest == None or smallest > n:
smallest = n
tot=tot+n
kount=kount+1
avg=tot/kount
print ("sum = ",tot,"Maximum = ", largest)
print("Minimum = ", smallest, "average = ",avg)
Expected output:
Enter a number (done to end) : 10
Enter a number (done to end) : 20
Enter a number (done to end) : 30
Enter a number (done to end) : abc
Invalid input
Enter a number (done to end) : 40
Enter a number (done to end) : 50
Enter a number (done to end) : done
sum = 150 Maximum = 50
Minimum = 10 average = 25.0
b. Take the following Python code that stores a string:
‘ str = ’X-DSPAM-Confidence:0.8475’
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number. 05
Ans:
str = 'X-DSPAM-Confidence:0.8475'
pos=str.find(':')
num=str[pos+1:]
num=float(num)
print(num)
0.8475
3.
a. Write a Python program to prompt for a file name, and then read through the file and print all the line starting with string “6thSem” striping the white space from left. 06
Ans:
fname=input(‘Enter file name : ‘)
file1=open(fname)
for line in file1:
line=line.lstrip()
if line.startswith('6thSem'):
print(line,end=' ')
Expected Output:
Enter file name : file1.txt
6thSem CSE section a
6thSem ISE section b
b. Write a Python program to find sum and average of a list of numbers using loops. 04
Ans:
list1=[10,20,30,40,50]
tot=0
x=0
for n in list1:
tot+=n
x+=1
avg=tot/x
print('Sum = ', tot, 'Average = ', avg)
Expected output:
Sum = 150 Average = 30.0
4.
a. Write a Python program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F 06
Ans:
marks = input('Enter score (0 to 1.0): ')
try:
score = float(marks)
if score > 1.0 or score < 0:
print ('Out of range')
grade=None
elif score >= .9:
grade='A'
elif score >= .8:
grade='B'
elif score >= .7:
grade='C'
elif score >= .6:
grade='D'
else:
grade='F'
print("Grade is",grade)
except:
print ('Bad score\n')
Expected Output:
Enter score (0 to 1.0): 90
Out of range
Grade is None
Again
Enter score (0 to 1.0): .8
Grade is B
b. Write a Python Program to find maximum in 3 numbers using nested if statement. 04
Ans:
#nested if - to find max in 3 numbers
n1 = input("Enter number 1: ")
n2 = input("Enter number 2: ")
n3 = input("Enter number 3: ")
n1,n2,n3=int(n1),int(n2),int(n3)
if n1 > n2:
if n1 > n3:
max=n1
else:
max=n3
else:
if n2 > n3:
max=n2
else:
max=n3
print('Maximum is %d' % max) #%d for integer of decimal number system
print('Largest is', max) #just printing value of variable max
5.
a. “Strings are immutable”, Explain the statement with example. 05
Ans:
“Strings are immutable” means value of a string variable cannot be modified. Aliasing the string object aliasing is not as much of a problem but we can’t change/modify characters of string.
>>> name='Paras'
>>> name[1]='o'
TypeError: 'str' object does not support item assignment
However ever we copy/add some contents of a string to another string.
>>>chat=’I love you’
>>> chat2 = chat[:7]+'her'
>>> # all characters of chat before 7 and adding ‘her’
>>> print(chat2)
I love her
b. Write a Python program to check where a string is palindrome. 05
Ans:
# Check whether a string is palindrome
def isPalindrome(str):
i = 0
j = len(str) - 1
while(i < len(str)/2): #comparing up to middle of string
if(str[i] != str[j]):
return False
i += 1
j -= 1
return True
s = input("Enter a string : ")
if(isPalindrome(s)):
print('Yes, "'+s+'" is a palindrome.')
else:
print('No, "'+s+'" is not a palindrome.')
Expected Output:
Enter a string : malayalam
Yes, "malayalam" is a palindrome.
Again
Enter a string : able was i ere i saw elba
Yes, "able was i ere i saw elba" is a palindrome.
6.
a. Define a function reverse_sum that takes a number as an input parameter ,finds the sum of all the digits in the number and returns the sum. 05
Ans:
def reverse_sum(num):
tot=0
while num != 0:
rem=num%10
tot+=rem
num//=10 #making it integer only
return tot
Expected output:
print('Sum of digits of',num,' = ', reverse_sum(num))
Sum of digits of 12345 = 15
b. Explain any two functions from the math module and two functions from random module with suitable examples. 05
Ans:
import math
This statement creates a module object named math
log10() - return logarithm base 10
>>> import math
>>> math.log10(1000)
3.0
sqrt() – returns square root of number
>>> math.sqrt(2)
1.414 #more than 10 digits after decimal
random module: The random module provides functions that generate pseudorandom numbers
>>> import random
>>> random.random()
0.12317805330561149
>>>
To choose an element from a sequence at random, you can use choice:
>>> names=['Paras','Ratan','Manohar','Manoj']
>>> random.choice(names)
'Manohar'
>>> n=[3,5,7,9]
>>> random.choice(n)
5
7.
a. Explain arithmetic, relational and logical operators with examples. 06
Ans:
Arithmetic operators:
The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation, as in the following examples:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
In Python 3.x result of division will be a floating point number. To get floored integer in division result we use //
Relational Operator/Boolean Experession
Boolean Expression (Returns True or false). Their type is bool.
== > < >= <= != is is not
>>> x=20
>>> y=30
>>> x is y
False
>>> x is not y
True
There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English.
and : both of the condition must be True
or: either of the condition should be True
not : negation of true is false and vice-versa
>>> x=20
>>> x > 0 and x < 10
False
>>> x > 0 or x < 10
True
>>> not x < 10
True
>>>
b. Write a Python Program to check whether a number is prime or not and print appropriate messages. 04
Ans:
#to check whether a number is prime
n=int(input("Enter number "))
prime=True
for d in range(2,int(n**(1/2))+1): #up to square root of n
if n%d == 0:
prime=False
break
if prime:
print(n, ' is prime')
else:
print(n,' is not prime')
Expected output:
Enter number 47
47 is prime
Again:
Enter number 48
48 is not prime
8.
a. Define a function to display Fibonacci series up to range given as argument. 05
Ans:
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
# Now call the function we just defined:
>>> fib(50)
0 1 1 2 3 5 8 13 21 34
b. Explain the inbuilt functions max(), min(), len(), int(), float(), str() with examples. 05
Ans:
max( ) – returns largest (number or character) in given arguments
min() – return smallest (number or character) in given arguments
len() – return length of argument in list or string
Examples:
>>> max(2,34,56,7)
56
>>> min(2,34,56,7)
2
>>> max('how are you')
'y'
>>> len('how are you')
11
>>> len(2,34,56,7)
TypeError: len() takes exactly one argument (4 given)
>>> a=[2,3,4,5]
>>> len(a)
4
Type conversion functions:
int() – converts integer written as string to integer
float() – converts number written as string to floating point value
str() – converts arguments as string
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to floating-point numbers:
>>> float(32) 32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'