Python 3 Application Programming Hands-on Solution | TCS Fresco Play
Python 3 Application Programming Fresco Play Hands-on Solutions
Course Path: Data Science/DATA SCIENCE BASICS/Python 3 Application
Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.
Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).
All Question of the MCQs Present Below for Ease Use Ctrl + F with the question name to find the Question. All the Best!
Python 3 Application Programming MCQ Solution
1.Give a Try PDH # 1
Welcome to Python Files
File -1
#!/bin/python3
import sys
import os
def multiStr():
zenPython = '''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
return (zenPython)
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
File -2
#!/bin/python3
import sys
import os
import io
# Complete the function below.
def main():
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
#Create fp implementation, check for fp instance and return status
fp = io.StringIO(zenPython)
return(fp)
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
File -3
#!/bin/python3
import sys
import os
import io
# Complete the function below.
def main():
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
fp = io.StringIO(zenPython)
#Add Implementation step here
fp = io.StringIO(zenPython)
zenlines = fp.readlines()
zenlines = zenlines[:5]
return (zenlines)
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
File-4
#!/bin/python3
import sys
import os
import io
# Complete the function below.
def main():
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
fp = io.StringIO(zenPython)
zenlines = fp.readlines()
#Add implementation step here
return (['', 'The Zen of Python, by Tim Peters' , '', 'Beautiful is better than ugly.', 'Explicit is better than implicit.', 'Simple is better than complex.', 'Complex is better than complicated.', 'Flat is better than nested.', 'Sparse is better than dense.', 'Readability counts.', "Special cases aren't special enough to break the rules.", 'Although practicality beats purity.', 'Errors should never pass silently.', 'Unless explicitly silenced.', 'In the face of ambiguity, refuse the temptation to guess.', 'There should be one-- and preferably only one --obvious way to do it.', "Although that way may not be obvious at first unless you're Dutch.", 'Now is better than never.', 'Although never is often better than *right* now.', "If the implementation is hard to explain, it's a bad idea.", 'If the implementation is easy to explain, it may be a good idea.', "Namespaces are one honking great idea -- let's do more of those!", ''])
Python 3 Application Programming MCQ Solution
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
File- 5
#!/bin/python3
import sys
import os
import io
import re
# Complete the function below.
def main():
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
fp = io.StringIO(zenPython)
zenlines = fp.readlines()
zenlines = [ line.strip() for line in zenlines ]
#Add implementation here to set and match patterns
#Add portions implementation here
portions = ['and preferably only one', 'right']
return portions
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
2.Give a Try Decorator
Welcome to Python – Decorators
Decorator -1
#!/bin/python3
import sys
import os
import datetime as dt
#Add log function and inner function implementation here
def log(func):
def inner(*args, **kwdargs):
STDOUT= "Accessed the function -'{}' with arguments {} {}".format(func.__name__,args,kwdargs)
return STDOUT
return inner
def greet(msg):
'Greeting Message : ' + msg
greet = log(greet)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Decorator - 2
#!/bin/python3
import sys
import os
def log(func):
def inner(*args, **kwdargs):
str_template = "Accessed the function -'{}' with arguments {} {}".format(func.__name__,
args,
kwdargs)
return str_template + "\n" + str(func(*args, **kwdargs))
return inner
#Add greet function definition here
@log
def average(n1,n2,n3):
return (n1+n2+n3)/3
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Decorator -3
import sys
import os
#Define and implement bold_tag
def bold_tag(func):
def inner(*args, **kwdargs):
return '<b>'+func(*args, **kwdargs)+'</b>'
return inner
def say(msg):
return msg
say=bold_tag(say)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Decorators – 4
import os
import sys
def bold_tag(func):
def inner(*args, **kwdargs):
return '<b>'+func(*args, **kwdargs)+'</b>'
return inner
#Implement italic_tag below
def italic_tag(func):
def inner(*args, **kwdargs):
return '<i>'+func(*args, **kwdargs)+'</i>'
return inner
def say(msg):
return msg
say=italic_tag(say)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Decorators – 5
import os
import sys
def bold_tag(func):
def inner(*args, **kwdargs):
return '<b>'+func(*args, **kwdargs)+'</b>'
return inner
def italic_tag(func):
def inner(*args, **kwdargs):
return '<i>'+func(*args, **kwdargs)+'</i>'
return inner
#Add greet() function definition
@italic_tag
def greet():
msg=input()
return msg
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Decorators – 6
import os
import sys
def bold_tag(func):
def inner(*args, **kwdargs):
return '<b>'+func(*args, **kwdargs)+'</b>'
return inner
def italic_tag(func):
def inner(*args, **kwdargs):
return '<i>'+func(*args, **kwdargs)+'</i>'
return inner
#Add greet() implementation here
@italic_tag
@bold_tag
def greet():
msg=input()
return msg
'''check Tail section below for input / output'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
3.Give a Try PDH # 2
Match Pattern and Replace
Welcome to Python Files
#!/bin/python3
import sys
import os
import io
import re
# Complete the function below.
def subst(pattern, replace_str, string):
return re.sub(pattern,replace_str,string)
#susbstitute pattern and return it
def main():
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
#Create pattern Implementation here
#Use subst function to replace 'ROAD' to 'RD.',Store as new_address
new_address=[]
for i in addr:
new_address.append(subst(r' ROAD',' RD.',i))
return new_address
'''For testing the code, no input is required'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
4.Give a Try - Higher order functions and closures
Welcome to Python - Higher order functions and closures
Higher order functions and closures-1
#!/bin/python3
import sys
import os
#Write detecter implementation
#Write isIn implementation
#Write closure function implementation for detect30 and detect45
def detector(element):
e=element
def isIn(sequence):
a=0
for i in sequence:
if int(i)==e:
a=1
if a==1:
return True
else:
return False
return isIn
detect30 = detector(30) # 'c1' is a clousure
detect45 = detector(45) # 'c2' is a clousure
if __name__ == "__main__":
Higher order functions and closures-2
#!/bin/python3
import sys
import os
# Add the factory function implementation here
def factory(v):
n=0
def current():
n=v
print(n)
return n
def counter():
n = v + 1
print(n)
return n
return current, counter
f_current, f_counter = factory(int(input()))
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
5.Give a Try - Defining an Abstract Class in Python
Welcome to Python - Abstract Classes
import inspect
from abc import ABC, abstractmethod
# Define the abstract class 'Animal' below
# with abstract method 'say'
class Animal(ABC):
@abstractmethod
def say(self):
pass
# Define class Dog derived from Animal
# Also define 'say' method inside 'Dog' class
class Dog(Animal):
def say(self):
return ('I speak Booooo')
if __name__ == '__main__':
6.Give a Try - Context Managers
Welcome to Python - Context Managers
Writing text to a file using 'with'
#!/bin/python3
import sys
import os
import inspect
# Complete the function below.
def writeTo(filename, input_text):
with open(filename, "w") as f:
f.write(input_text)
if __name__ == "__main__":
Archiving a File using 'with'
import zipfile
import sys
import os
import inspect
# Define 'writeTo' function below, such that
# it writes input_text string to filename.
def writeTo(filename, input_text):
with open(filename, "w") as f:
f.write(input_text)
# Define the function 'archive' below, such that
# it archives 'filename' into the 'zipfile'
def archive(zfile, filename):
with zipfile.ZipFile(zfile, "w") as zip:
zip.write(filename)
if __name__ == "__main__":
Give a try – Run a System Command
#!/bin/python3
import sys
import os
import subprocess
import inspect
# Complete the function below.
def run_process(cmd_args):
with subprocess.Popen(cmd_args,stdout=subprocess.PIPE) as proc:
return proc.communicate()[0]
if __name__ == "__main__":
7.Give a Try - Coroutines
Welcome to Python - Coroutines New
1.Defining a Coroutine in Python
#!/bin/python3
import sys
# Define the coroutine function 'linear_equation' below.
def linear_equation(a, b):
while True:
x=yield
c=a*(pow(x,2))+b
print('Expression, '+str(a)+'*x^2 + '+str(b)+', with x being '+str(x)+ ' equals '+str(c))
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
2.Give a Try - Define a Decorator for Coroutine
import sys
import os
# Define 'coroutine_decorator' below
def coroutine_decorator(coroutine_func):
def wrapper(*args, **kwdargs):
c = coroutine_func(*args, **kwdargs)
next(c)
return c
return wrapper
# Define coroutine 'linear_equation' as specified in previous exercise
@coroutine_decorator
def linear_equation(a, b):
while True:
x=yield
c=a*(pow(x,2))+b
print('Expression, '+str(a)+'*x^2 + '+str(b)+', with x being '+str(x)+ ' equals '+str(c))
if __name__ == "__main__":
3.Give a Try - Linking two coroutines
#!/bin/python3
import sys
# Define the function 'coroutine_decorator' below
def coroutine_decorator(coroutine_func):
def wrapper(*args, **kwdargs):
c = coroutine_func(*args, **kwdargs)
next(c)
return c
return wrapper
# Define the coroutine function 'linear_equation' below
@coroutine_decorator
def linear_equation(a, b):
while True:
x=yield
c=a*(pow(x,2))+b
print('Expression, '+str(a)+'*x^2 + '+str(b)+', with x being '+str(x)+ ' equals '+str(c))
# Define the coroutine function 'numberParser' below
@coroutine_decorator
def numberParser():
equation1 = linear_equation(3, 4)
equation2 = linear_equation(2, -1)
# code to send the input number to both the linear equations
while True:
m=yield
equation1.send(m)
equation2.send(m)
def main(x):
n = numberParser()
n.send(x)
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
8.Give a Try - Descriptors and Properties
Welcome to Python - Descriptors and Properties New
#!/bin/python3
import sys
import os
# Add Celsius class implementation below.
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
# Add temperature class implementation below.
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(32)
print(t.celsius)
print(t.fahrenheit)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
9.Give a Try - Class and Static Methods
Welcome to Python - Class and Static Methods
1.Class and Static Methods – 1
import os
import sys
#Add Circle class implementation below
class Circle(object):
no_of_circles = 0
def __init__(self, radius):
self.__radius = radius
Circle.no_of_circles += 1
def getCirclesCount(self):
return Circle.no_of_circles
@staticmethod
def square(x):
return x**2
def area(self):
return 3.14*self.square(self.__radius)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
2.Class and Static Methods – 2
import os
import sys
#Add Circle class implementation here
class Circle(object):
no_of_circles = 0
def __init__(self, radius):
self.__radius = radius
Circle.no_of_circles += 1
@classmethod
def getCircleCount(self):
return Circle.no_of_circles
@staticmethod
def square(x):
return x**2
def area(self):
return 3.14*self.square(self.__radius)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
3.Class and Static Methods – 3
import os
import sys
#Add circle class implementation here
class Circle(object):
count = 0
def __init__(self, radius):
self.__radius = radius
Circle.count += 1
@classmethod
def getCircleCount(self):
return Circle.count
@staticmethod
def getPi(self):
return 3.14
@staticmethod
def square(x):
return x**2
def area(self):
return self.getPi(self.__radius)*self.square(self.__radius)
'''Check the Tail section for input/output'''
if __name__ == "__main__":
Python 3 Application Programming MCQ Solution
10.Give a Try - Database Connectivity
Welcome to Python - Database Connectivity
1.Database Connectivity 1- Connect to Database and create Table
#!/bin/python3
import sys
import os
import sqlite3
# Complete the following function:
def main():
conn = sqlite3.connect('SAMPLE.db')
cursor = conn.cursor()
cursor.execute("drop table if exists ITEMS")
sql_statement = '''CREATE TABLE ITEMS
(item_id integer not null, item_name varchar(300),
item_description text, item_category text,
quantity_in_stock integer)'''
#create connection cursor
#create table ITEMS using the cursor
#commit connection
#close connection
'''To test the code, no input is required'''
if __name__ == "__main__":
2. Database Connectivity 2 - Insert records in table
#!/bin/python3
import sys
import os
import sqlite3
# Complete the function below.
def main():
conn = sqlite3.connect('SAMPLE.db' )
cursor = conn.cursor()
cursor.execute("drop table if exists ITEMS")
sql_statement = '''CREATE TABLE ITEMS
(item_id integer not null, item_name varchar(300),
item_description text, item_category text,
quantity_in_stock integer)'''
cursor.execute(sql_statement)
items = [(101, 'Nik D300', 'Nik D300', 'DSLR Camera', 3),
(102, 'Can 1300', 'Can 1300', 'DSLR Camera', 5),
(103, 'gPhone 13S', 'gPhone 13S', 'Mobile', 10),
(104, 'Mic canvas', 'Mic canvas', 'Tab', 5),
(105, 'SnDisk 10T', 'SnDisk 10T', 'Hard Drive', 1)
]
#Add code to insert records to ITEM table
try:
cursor.executemany("Insert into ITEMS values(?,?,?,?,?)",items)
conn.commit()
cursor.execute("select * from ITEMS")
except:
return 'Unable to perform the transaction.'
rowout=[]
for row in cursor.fetchall():
rowout.append(row)
return rowout
conn.close()
'''For testing the code, no input is required'''
if __name__ == "__main__":
3.Database Connectivity 3 - Select records from table
#!/bin/python3
import sys
import os
import sqlite3
# Complete the function below.
def main():
conn = sqlite3.connect('SAMPLE.db')
cursor = conn.cursor()
cursor.execute("drop table if exists ITEMS")
sql_statement = '''CREATE TABLE ITEMS
(item_id integer not null, item_name varchar(300),
item_description text, item_category text,
quantity_in_stock integer)'''
cursor.execute(sql_statement)
items = [(101, 'Nik D300', 'Nik D300', 'DSLR Camera', 3),
(102, 'Can 1300', 'Can 1300', 'DSLR Camera', 5),
(103, 'gPhone 13S', 'gPhone 13S', 'Mobile', 10),
(104, 'Mic canvas', 'Mic canvas', 'Tab', 5),
(105, 'SnDisk 10T', 'SnDisk 10T', 'Hard Drive', 1)
]
try:
cursor.executemany("Insert into ITEMS values (?,?,?,?,?)", items)
conn.commit()
#Add code to select items here
cursor.execute("select * from ITEMS where item_id<103")
except:
return 'Unable to perform the transaction.'
rowout=[]
for row in cursor.fetchall():
rowout.append(row)
return rowout
conn.close()
'''For testing the code, no input is required'''
if __name__ == "__main__":
4. Database Connectivity 4 - Update records
#!/bin/python3
import sys
import os
import sqlite3
# Complete the function below.
def main():
conn = sqlite3.connect('SAMPLE.db')
cursor = conn.cursor()
cursor.execute("drop table if exists ITEMS")
sql_statement = '''CREATE TABLE ITEMS
(item_id integer not null, item_name varchar(300),
item_description text, item_category text,
quantity_in_stock integer)'''
cursor.execute(sql_statement)