VTU Exam Question Paper With Solution of 18CS55 Application Development Using Python (ADP) March-2021
VTU Exam Question Paper With Solution of 18CS55 Application Development Using Python (ADP) March-2021
Python(18CS55)
MODULE 1
1 a. Demonstrate with example print(), input() and string replication. 6M
Ans # A Hello world program
print("Hello World")
print("What is your name?") #1
my_name = input() #2
print("It is good to meet you, "+my_name)
# obtain user’s lucky number
lucky_num=int(input(“Enter your lucky number: “))
#print out ‘hello’ lucky_num number of times
print(‘hello’*lucky_num) #3
Output:
What is your name?
Jenna
It is good to meet you, Jenna
Enter your lucky number : 3
hellohellohello
#1 print()
► print('Hello world!')
► print('What is your name?') # ask for their name
► print() is a function.
► The string to be displayed is passed as a value to the function
► Value passed to a function is called an argument.
► The quotes just begin and end the string and are not printed.
► It can be used to insert a blank line: print()
#2 input()
► Waits for user to type something and hit “ENTER”.
► myName=input()
► Assigns a string to a user.
► print(“It is good to meet you, ”+myName)
► A single string is passed to the print() function.
#3 String Replication
► String Replication operator: When used with one string and one integer values,
it replicates the string.
► >>> "hello"*3
'alicealicealicealice'
► >>> 4*"bob"
'bobbobbobbob'
>>> "alice"*"bob"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
b Explain elif, for, while, break and continue statements in Python with 10
examples of each m
if name== “Alice”:
print (“Alice”)
elif age <12:
print(“You’re just a kid”)
elif age < 5:
print(“you’re just a baby”)
while
break
► break : will break out of a loop when it is encountered.
name = ''
while True:
name = input("Enter your name:")
if name == 'Max':
break
print('Thank you')
continue
► On encountering a continue statement, program execution immediately
jumps back to the start of the loop.
► Reevaluates the condition.
► This is similar to what happens when execution reaches the end of t
►
►
► he loop.
while True:
print('Who are you?')
name = input()
if name != 'Max':
continue
print('Hello Max. What is your password?')
pswd = input()
if pswd == '123':
break
print('Access granted')
evenodd.py
if num % 2 == 0:
print(“Number is Even”)
else:
print(“Number is Odd”)
Output:
> python evenodd.py
4
Number is Even
2.a. How can we pass parameters in user defined functions? Explain with suitable 5m
examples.
Ans. ► A function is a mini-program within a program.
► Purpose: group code that gets executed multiple times
► Avoid duplication of code
► Deduplication makes your programs shorter, easier to read, and easier to
update
► Pass values to functions (parameters)
► A parameter is a variable that an argument is stored in when a function is
called
► hello(“Alice”) : variable name is automatically set to “Alice”.
► Value stored in parameter is destroyed when function returns
► The scope is local
def hello(name):
print("Hello " + name)
hello("Alice")
hello("Bob")
print(name)
Output:
Hello Alice
Hello Bob
NameError: name 'name' is not defined
b. Explain local and global scope with local and global variables 8m
Ans. ► Local scope: Parameters and variables that are assigned in a called function
► Local variables : exists in a local scope
► Global scope : Variables that are assigned outside all functions
► Global variable : exists in a global scope
► Scope : container for variables
► When scope is destroyed, the variables are forgotten
► Global scope is created when the program begins.
► When program terminates: global scope is destroyed.
► Local scope is created whenever function is called.
► Destroyed when function returns.
► Code in the global scope cannot use any local variables
► a local scope can access global variables
► Code in a function’s local scope cannot use variables in any other local
scope.
► Permitted to use same name for different variables if they are in different
scopes.
► Reason for scope
► Easier to debug.
► Always good practice to use local variables for long programs.
► Local Variables Cannot Be Used in the Global Scope
► Only global variables can be used in global scope.
► Local Scopes Cannot Use Variables in Other Local Scopes
► local variables in one function are completely separate from the local
variables in another function
def foo():
x=3
print(x) # Error as x is not defined in global scope
def foo():
x = 3 # belongs to scope of foo
def bar():
x+=2 # error : as x is not defined in bar()
foo()
bar()
temp_conv.py
try:
temp_celsius = float(input(“Enter temperature in Celsius:”) )
temp_fahrenheit = (temp_celsius *(9/5))+32
print(“Temperature in Fahrenheit is : “, temp_fahrenheit)
except:
print(“Enter a valid value for temperature”)
Output:
> python temp_conv.py
Enter temperature in Celsius: 45
Temperature in Fahrenheit is : 113
b. How is tuple different from a list and which function is used to convert list to 5m
a tuple.
Ans. ► Tuples are typed with parantheses, ( and )
► Tuples are immutable
► In other aspects they are identical to lists.
► TypeError is generated if there is an attempt to modify a tuple.
► A singleton tuple needs to be specified with a value followed by a comma
► Otherwise, Python will interpret it as a value inside a parantheses.
► Use tuples to convey a message that the sequence is not meant to change.
► To use an ordered sequence that does not change, use a tuple.
► Since contents of tuples do not change, Python can slightly optimize code that
uses tuples as compared to lists.
>>> a=tuple([1,2,3])
>>> a
(1,2,3)
>>> subjects=('dbms','os','python')
>>> subjects
('dbms','os','python') # indexes can be used to access items in tuples
>>> subjects[1]
'os'
>>> subjects[1:] # tuples can be sliced the same way as lists because
# slicing returns a new tuple
('os','python')
>>>subjects[1]=‘java’ # tuples are immutable, this assignment is acceptable in lists,
# In tuples, it results in an error.
Type Error
►
tic-tac.py
tictac = {'low-L':' ','low-M':' ','low-R':' ',
'mid-L':' ','mid-M':' ','mid-R':' ',
'top-L':' ','top-M':' ','top-R':' '}
def print_board():
print(tictac['top-L']+'|'+tictac['top-M']+'|'+tictac['top-R'])
print('-+-+-')
print(tictac['mid-L']+'|'+tictac['mid-M']+'|'+tictac['mid-R'])
print('-+-+-')
print(tictac['low-L']+'|'+tictac['low-M']+'|'+tictac['low-R'])
print_board()
Output:
4.a. Discuss get(), items(), keys(), values() dictionary methods in Python with 8m
examples.
Ans. ► Tedious to check if key exists before accessing the value.
► get() : takes 2 arguments
► Key of the value to retrieve
► Fallback value to return if the key does not exist.
>>> items={'pen':5, 'stapler':1, 'marker': 3}
>>> print("I have",items.get('pen',0), 'pens')
I have 5 pens
>>> print("I have",items.get('pencil',0), 'pencils')
I have 0 pencils
Sample output
#items={'pen':5, 'stapler':1, 'marker': 3}
python items_get.py
Enter item(blank to quit):
stapler
Number:3
Enter item(blank to quit):
eraser
Number:4
Enter item(blank to quit):
{'pen': 5, 'stapler': 4, 'marker': 3, 'eraser': 4}
Ans.
Longestword.py
sentence = input()
sentence=sentence.lower()
Sample output:
>python Longestword.py
Application Development using Python
development, 11
sentence =input()
sentence = sentence.lower()
words = sentence.lower()
words.sentence.split()
wl = {}
for w in words:
wl[w] = len(w)
wl_list.sort()
print(wl_list[-1][1],’:’, wl_list[-1][0]) # prints the word and corresponding length
MODULE 3
5 a. What are regular expressions? Describe question mark, star, plus and dot 9m
regex symbols with suitable Python code snippet
Ans. Regular expressions are used for pattern matching. They have special characters that
are interpreted for the purpose of matching patterns in text.
► 1. Import the regex module with import re.
► 2. Create a Regex object with the re.compile() function. (Remember to use
a raw string.)
► 3. Pass the string you want to search into the Regex object’s search()
method.
► This returns a Match object.
► 4. Call the Match object’s group() method to return a string of the actual
matched text.
Wildcard character
► . (or dot) character : a wildcard and will match any character except for a
newline
► .* “anything.”
► . “any single character except the newline”
► * : “zero or more of the preceding character”
► Uses greedy mode
► Non greedy mode : .*?
b. With code snippet, explain saving variables using the shelve module and 6m
PPrint Pformat() functions.
Ans. ► Used to save variables in your Python programs to binary shelf files
► program can restore data to variables from the hard drive.
► Shelve module : allows you to Save and Open features to your program.
► To read and write data, call shelve.open() and pass file name.
► Notice that 3 files, 'mydata.bak', 'mydata.dat', 'mydata.dir‘ get created in the
current working directory. (On OS X, mydata.db is created)
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> topics=['read files','write files','append']
>>> shelfFile['topics']=topics
>>> shelfFile.close()
>>> os.listdir()
mydata.bak mydata.dat mydata.dir
>>> sf= shelve.open('mydata')
>>> list(sf.keys())
[‘topics’]
>>> list(sf.values())
['read files','write files','append']
c. Write a program that reads a string with five characters which starts with ‘a’ 5m
and ends with ‘z’. Print search successful if pattern matches string.
Search.py
import re
regex= re.compile(r'^a. .. z$')
str = input()
if regex.search(str):
print("Search Successful")
else:
print("Search unsuccessful")
Sample output 1
> python Search.py
Hello
Search unsuccessful
Sample output 2
> python Search.py
abyzz
Search Successful
Sample output 3
>python Search.py
abeizz
Search unsuccessful
In sample output 1, even though string is of 5 characters, it does not start nor end
with a and z
In sample output 2, search is successful because the string comprises of 5 characters
beginning with ‘a’ and ending with ‘z’
In sample output 3, search is unsuccessful because even though the string starts and
ends with ‘a’ and ‘z’, it consists of less than 5 characters.
Go
Clicking the Go button will cause the program to execute normally until it
terminates or reaches a breakpoint.
Step
Clicking the Step button will cause the debugger to execute the next line
of code and then pause again.
Over
Clicking the Over button will execute the next line of code, similar to the
Step button. if the next line of code is a function call, the Over
button will “step over” the code in the function
Out
Clicking the Out button will cause the debugger to execute lines of code
at full speed until it returns from the current function.
Quit
If you want to stop debugging entirely and not bother to continue executing
the rest of the program, click the Quit button.
c. What is meant by compressing files? Explain reading, extracting, and 7m
creating ZIP files with code snippet
Ans. ► Compressing a file reduces its size, which is useful when transferring it over
the Internet.
► namelist() method that returns a list of strings for all the files and folders
contained in the ZIP file.
► Can be passed to getinfo() of ZipFile
► To retrieve information about the particular file
MODULE 4
7 a. What is class, object, attributes. Explain copy.copy() with an example. 6m
Ans. ► A user-defined type is also called a class.
► Let’s say you wanted to represent a point in 2D space (x,y)
► Store it in 2 variables, x and y
► Store it as coordinates in a list or a tuple
► Create a new type to represent points a objects.
► Indicates that Point is a kind of object which is a built in type.
► Point is at the top level, so full name is main .Point
► Creating a new object is called instantiation.
► The object is an instance of the class.
► When you print an instance, you will get information on
► What class it belongs to
► Address in memory
Copy.copy()
Consider a function increment() that takes the time object (hour, minute, second) and
seconds as the second parameter to add the seconds to the time object.
class Time:
pass
# modifier
def increment(t,sec):
t.second+=sec
if t.second>=60:
e_m, e_s = (t.second)//60, (t.second)%60
t.second = e_s
t.minute+=e_m
# pure function
def increment_pure(t,sec):
inc_t=Time()
inc_t.hour=t.hour
inc_t.second=t.second+sec
if inc_t.second>=60:
e_m, e_s = (inc_t.second)//60, (inc_t.second)%60
inc_t.second = e_s
inc_t.minute=t.minute+e_m
return inc_t
t = Time()
t.hour,t.minute,t.second=11,30,30
increment(t,180)
print_time(t)
t = Time()
t.hour,t.minute,t.second=11,30,30
inc_t = increment_pure(t,180)
print_time(inc_t)
In the modifier version, the seconds are incremented to the t object. In the pure
version of increment, the original t object is not modified, but the seconds
incremented to time is returned.
c. Use the datetime module to write a program that gets the current date and 6m
prints the day of the week.
Ans. import datetime
today=datetime.datetime.today()
print(today)
print(today.weekday())
Output:
2021-03-12 15:19:10.966676
4
Explanation: from datetime, the today() function returns the current date and time
as an object.
The weekday() function returns the day of the week where Monday is 0 and Sunday is
6. Because 12.3.2021 is falling on Friday, it returns 4.
t1=Time(2,45,3)
t2 = Time(3,15,2)
print(t1+t2)
# Output 06:00:05
Inheritance is a useful feature. Some programs that would be repetitive without inheritance
can be written more elegantly with it.
Inheritance can facilitate code reuse, since you can customize the behavior of parent classes
without having to modify them. In some cases, the inheritance structure reflects the natural
structure of the problem, which makes the program easier to understand.
All the methods in the superclass are accessible to the child class. The child class may define
more specialized methods in addition to the methods in the super class.
Person
class Student(Person):
def __init (self, aadhar_no, name, dob, gender, usn, branch, year):
super(). init (aadhar_no,name, dob, gender)
self.usn = usn
self.branch = branch
self.year = year
s1 = Student(‘87024586’,’Kumar’,’07-08-1994’,’M’,’CSE’, 2014)
The above code snippet demonstrates how Student inherits from Person.
Explanation:
The parent class Is Person. It has a init to instantiate its instance variables, aadhar
number, name, date of birth(dob) and gender
A specialization of Person is the Student class which has all the attributes of a Person and
in addition, student specific attributes such as USN, branch and year (of admission).
When we instantiate a student object, we may pass all the attributes s1 = Student
(‘87024586’,’Kumar’,’07-08-1994’,’M’,’CSE’, 2014)
When we are instantiating the variables in the Student class, we can invoke the
superclass’s init by using super() to pass the attributes that belong to the super class
c. Write a function called print_time that takes a time object and prints it in the 4m
form of hour: minute: second
Ans. class Time:
def init (self, hour=0,minute=0,second=0):
self.hour=hour
self.minute=minute
self.second=second
def print_time(t):
print( '%.2d:%.2d:%.2d'%(t.hour,t.minute,t.second) )
t1=Time (2,45,3)
print_time(t1)
Sample output:
02:45:03
Explanation:
The print function uses %0.2d to add a leading 0 if there is a single digit for hour,
minute or second.
The dot notation is used to access the attributes of the time object, hour, minute and
second respectively.
MODULE 5
9 a. Explain parsing HTML with the BeautifulSoup Module with code snippet for 9m
creating finding an element and getting data.
Ans. Parsing HTML with Beautiful Soup module
► pip install beautifulsoup4
► Download Automate the Boring Stuff with Python, 2nd Edition | No Starch
Press and store it as example.html
► We’ll read from a html page in the hard disk
► Creating a BeautifulSoup
Selector match
Let sample.html be
<html>
<head> <title> Sample page </title>
</head>
<body>
<h1> Welcome </h1>
</html>
import bs4
fh = open('sample.html')
soup = bs4.BeautifulSoup(fh.read())
elems = soup.select('#one')
print(elems[0].getText())
output:
First Paragraph
In the above code snippet, the element is selected by ID. The soup.select() is used to
find the element. We can then extract the attributes of the element. The getText()
method will extract the text within the p tag.
b. What methods do Selenium’s web element object have for simulating mouse 6m
clicks and keyboard keys. Explain with python code snippet.
Ans Clicking Elements:
► method can be used to follow a link
► make a selection on a radio button
► click a Submit button
► trigger anything that happens when an element is clicked by the mouse.
from selenium import webdriver
browser =
webdriver.Chrome(executable_path=r"C:\Users\Admin\Downloads\chromedriver.exe"
)
browser.get('https://www.crummy.com/software/BeautifulSoup/bs4/doc/')
try:
linkElem = browser.find_element_by_link_text('Sphinx')
print(type(linkElem))
linkElem.click()
except:
print('Was not able to find an element with that name.')
► These keys are stored in selenium.webdriver.common.keys module.
► run from selenium.webdriver.common.keys import Keys
Explanation:
► First we import openpyxl package.
► It needs to be installed using pip install openpyxl. It works on files from
Microsoft Excel or free alternatives like LibreOffice Calc, OpenOffice Calc work
with .xlsx files
► spreadsheet document called workbook
► openpyxl.open() returns an object of type workbook which we save in wb
► Each workbook can have multiple sheets.
► The sheet that is currently being viewed is called the active sheet.
► To obtain a reference to the active sheet we use wb.active.
► A sheet can be directly accessed using the name also such as, wb[‘Sheet1’]
► Cell object has a value attribute that contains value
► Also has row, column, and coordinate attributes
► To access using coordinate, we can specify the column letter and the row
number that starts from 1.
► sheet['A1'] returns the cell in the first row and first column. Sheet[‘C3’] returns
cell in the 3rd column and 3rd row.
► Specifying column by letter can be difficult : because after Z it becomes AA,
AB, and so on.
► cell() method allows passing a number.
► sheet.cell(row=1,column=2) allows us to access a cell using row number and
column number.
10a. Write a program to get a list of all files with the .pdf extension in the current 6m
working directory and sort them.
Ans. import os,re
lstFiles = os.listdir()
regexpdf=re.compile('\.pdf$')
pdf_files = []
for file in lstFiles:
if regexpdf.search(file):
pdf_files.append(file)
pdf_files.sort()
print(pdf_files)
Sample Output:
['LP.pdf', 'Syll.pdf', 'Syll_protected.pdf', 'VTUTT.pdf', 'conf.pdf', 'coverletter-
netapp.pdf', 'encrypted.pdf', 'marked.pdf', 'merged.pdf', 'rotated.pdf',
'watermark.pdf']
Explanation
We will import 2 packages, os and re.
os.listdir(path) : returns a list of filename strings for each file in the path
argument
If we do not pass any argument to listdir() it returns list of filename strings in
the current working directory.
We write a regular expression for files ending with .pdf. Since the dot is a
special character in a regular expression, we escape the special meaning to
match a literal dot in the file name. next it matches pdf at the end of the
string.
A for loop is set up to iterate through the file names from os.listdir(). Each file
name is checked with the patter in regexpdf variable. If the search is
successful, then the file name string is added to a list pdf_files.
The contents of pdf_files is sorted by invoking sort()
Since lists are mutable, the sort() is done in place.
The sorted list is then printed.
b. Demonstrate the json module with the python program. 6m
Ans. ► handles all the details of translating between a string with JSON data and
Python values for the json.loads() and json.dumps()
► JSON can’t store every kind of Python value
► Following data types are possible : strings, integers, floats, Booleans,
lists, dictionaries, and NoneType.
► JSON cannot represent Python-specific objects
► File objects, CSV Reader or Writer objects, Regex objects, or Selenium
WebElement objects.
► json.loads(): translate a string containing JSON data into a Python value
► loads: load string
► JSON strings always use double quotes
► It returns a Python dictionary.
► Dictionary is not ordered
► So key value pair may appear in different order.
>>> str = '{"TeamID":"CS003", "Topic":"Review 1","Number of attendees":5,"Meet
Link":null, "isStarted":false}'
>>> import json
>>> val = json.loads(str)
>>> val
{'TeamID': 'CS003', 'Topic': 'Review 1', 'Number of attendees': 5, 'Meet Link': None,
'isStarted': False}
► json.dumps() function : translate a Python value into a string of JSON-
formatted data
► dumps : dump string
► value can only be one of the following basic Python data types:
► dictionary, list, integer, float, string, Boolean, or None.
>>> d={'TeamID': 'CS003', 'Topic': 'Review 1', 'Number of attendees': 5, 'Meet Link':
None, 'isStarted': False}
>>> str = json.dumps(d)
>>> str
'{"TeamID": "CS003", "Topic": "Review 1", "Number of attendees": 5, "Meet Link":
null, "isStarted": false}'
c. What are the advantages of CSV file? Explain the Reader objects and Writer 8m
objects with python code.
Ans. ► Each line in a CSV file represents a row in the spreadsheet.
► Commas separate the cells in the row
► CSV files are simple, they don’t have many features of an excel spreadsheet.
► Don’t have types for their values—everything is a string
► Don’t have settings for font size or color
► Don’t have multiple worksheets
► Can’t specify cell widths and heights
► Can’t have merged cells
► Can’t have images or charts embedded in them
Advantage of CSV
► Simplicity
► widely supported by many types of programs
► can be viewed in text editors (including IDLE’s editor)
► straightforward way to represent spreadsheet data.
► CSV files also have their own set of escape characters to allow commas and
other characters to be included as part of the values
► split() method does not handle these special characters.
► Use csv module
► Avoid opening as text file and use split().
Reader() function
► csv.reader() function
► This returns a Reader object
► You can’t directly pass a filename to the reader() function
► Notice that we get a list of lists when we convert the data to a list.
>>> import csv
>>> import os
>>> os.chdir('Documents')
>>> fh = open('sample_csv.csv')
>>> reader = csv.reader(fh)
>>> data =list(reader)
>>> data
[['4/5/2015 1:34:02 PM ', 'Apples', '73'], ['4/5/2015 1:34:02 PM ', 'Cherries',…
>>> data[0][1]
'Apples'
>>> data[1][0]
'4/5/2015 1:34:02 PM '
► For large CSV files, use a for loop.
► This avoids loading the entire file into memory at once.
► The reader can be looped over once.
► To read again, open the file again and obtain a reader object.
>>> fh = open('sample_csv.csv')
>>> reader = csv.reader(fh)
>>> for row in reader:
... print('Row #%d %s'%(reader.line_num,row))
...
Row #1 ['4/5/2015 1:34:02 PM ', 'Apples', '73']
Row #2 ['4/5/2015 1:34:02 PM ', 'Cherries', '85']
….
Writer object
► A Writer object lets you write data to a CSV file.
► pass it 'w' to open a file in write
mode
► pass to csv.writer() - creates a
writer object
► In Windows, pass empty string
as newline character otherwise output
will be double spaced.
► writerow() takes a list argument