Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
90% found this document useful (20 votes)
43K views

Fresco Code Python Application Programming

This document contains summaries of 7 hands-on exercises involving Python files and concepts like files, databases, decorators, classes, and abstract classes. The exercises cover opening and reading files, connecting to and manipulating a SQLite database, defining decorator functions, implementing an abstract class, and using class and static methods. Code snippets are provided for each hands-on exercise to demonstrate the concepts.

Uploaded by

Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
90% found this document useful (20 votes)
43K views

Fresco Code Python Application Programming

This document contains summaries of 7 hands-on exercises involving Python files and concepts like files, databases, decorators, classes, and abstract classes. The exercises cover opening and reading files, connecting to and manipulating a SQLite database, defining decorator functions, implementing an abstract class, and using class and static methods. Code snippets are provided for each hands-on exercise to demonstrate the concepts.

Uploaded by

Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Handson #1 Give a Try PDH # 1- Welcome to Python Files :

File 2 :

fp = io.StringIO(zenPython)
return fp

File 3 :

fp = io.StringIO(zenPython)
zenlines=fp.readlines()[:5]
return(zenlines)

File 4:

zenlines = [ line.strip() for line in zenlines ]


return zenlines

File 5:

portions=re.findall(r"[-*] ?([^-*].*?) ?[-*]",zenPython)

m
==============================================

er as
Handson #2 - Give a Try PDH # 2 -

co
eH w
finalw = [re.sub(r'\bROAD\b', 'RD.', x) for x in addr]

o.
return finalw rs e
ou urc
=================================================
Handson #3 - Welcome to Python Database Connectivity

File 1 :
o
aC s

import sqlite3
v i y re

def main():
conn = sqlite3.connect('SAMPLE.db')
#create connection cursor
cursor = conn.cursor()
ed d

#create table ITEMS using the cursor


ar stu

query = "CREATE TABLE ITEMS(item_id , item_name , item_descr , iption ,


item_category , quantity_in_stock)"

cursor.execute(query)
#commit connection
sh is

conn.commit()
#close connection
Th

conn.close()

File 2 :

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

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
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

sql = '''INSERT INTO ITEMS VALUES(?,?,?,?,?)'''

try:

cursor.executemany(sql,items)

cursor.execute("select * from ITEMS")


except:
return 'Unable to perform the transaction.'
rowout=[]
for row in cursor.fetchall():

m
rowout.append(row)

er as
return rowout

co
conn.close()

eH w
File 3:

o.
rs e
cursor.execute("select * from ITEMS WHERE item_id < 103")
ou urc
File 4:

cursor.executemany("update ITEMS set quantity_in_stock = ? where item_id = ?",


o

[(4, 103),
aC s

(2, 101),
v i y re

(0, 105)])

File 5:

query1 = "delete from ITEMS where item_id = 105"


ed d

cursor.execute(query1)
ar stu

===========================================

Handson #4 : Higher Order Function and Closures1


sh is

File 1 - Closures
Th

def detecter(element):
def isIn(sequence):
temp = 0
for i in sequence:
if i == element:
temp = temp+1
if temp > 0:
return True
else:
return False

return isIn

#Write closure function implementation for detect30 and detect45

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
detect30 = detecter(30)
detect45 = detecter(45)

File 2 :

def factory(n=0):

def current():
return n

def counter():
nonlocal n
n += 1
return n

return current, counter

f_current,f_counter = factory(int(input()))

===================================================

m
Handson #5 : Welcome to Python - Decorators

er as
[https://repl.it/@nimishmol/frescodecoratorfinaltest#main.py]

co
eH w
File 1:

o.
def log(func): rs e
def inner(*args, **kwdargs):
ou urc
str_template = "Accessed the function -'{}' with arguments {}
".format(func.__name__,args)+"{}"
return str_template
return inner
o
aC s
v i y re

@log
def greet(msg):
return msg
ed d

File 2:
ar stu

@log
def average(n1,n2,n3):
return (n1+n2+n3)/3
sh is

File 3:
Th

def bold_tag(func):

def inner(*args, **kwdargs):


return '<b>'+func(*args, **kwdargs)+'</b>'

return inner

@bold_tag
def say(msg):
return msg

File 4:

#Implement italic_tag below


def italic_tag(func):

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
def inner(*args, **kwdargs):
return '<i>'+func(*args, **kwdargs)+'</i>'

return inner

#Implement italic_tag below

@italic_tag
def say(msg):
return msg

File 5:

@italic_tag
def greet():
msg = 'Hello World! Welcome to Python Programming Language' #input()
return msg

File 6:

@italic_tag
@bold_tag

m
er as
#Add greet() implementation here

co
def greet():

eH w
return input()

o.
=======================================================
rs e
ou urc
Handson # 6 : Welcome to Python - Give a Try - Defining an Abstract Class in
Python

class Animal(ABC):
o

@abstractmethod
aC s

def say(self):
v i y re

pass
# Define class Dog derived from Animal
# Also define 'say' method inside 'Dog' class
class Dog(Animal):
def say(self):
ed d

super().say()
ar stu

return("I speak Booooo")

=====================================================

Handson # 7 : Welcome to Python - Class and Static Methods


sh is

File 1 :
Th

class Circle:
no_of_circles = 0
def __init__(self,radius):
self.radius = radius
Circle.no_of_circles += 1
def area(self):
return round((3.14*self.radius*self.radius),2)

File 2 :

class Circle:
no_of_circles = 0
def __init__(self,radius):
self.radius = radius
Circle.no_of_circles += 1

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
def area(self):
return round((3.14*self.radius*self.radius),2)
@classmethod
def getCircleCount(self):
return Circle.no_of_circles

File 3:

class Circle(object):
no_of_circles = 0
def __init__(self,radius):
self.radius = radius
Circle.no_of_circles += 1
@staticmethod
def getPi():
return 3.14
def area(self):
return round((self.getPi()*self.radius*self.radius),2)
@classmethod
def getCircleCount(self):
return Circle.no_of_circles

m
==============================================

er as
co
Handson # 8 Give a Try - Context Managers

eH w
File 1 :

o.
with open(filename , 'w') as fp:
rs e
ou urc
content = fp.write(input_text)

File 2 :
o

def writeTo(filename, input_text):


aC s

with open(filename , 'w') as fp:


v i y re

content = fp.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:
ed d

# writing each file one by one


ar stu

zip.write(filename)

File 3 :

with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


sh is

as p:
Th

out, err = p.communicate()


return out

=====================================================

Handson # 9 Give a Try - Coroutines

File 1 :

while True:
n =yield
t = (a*(n**2))+b
string = "Expression, "+str(a)+"*x^2 + "+str(b)+", with x being "+str(n)
+" equals "+str(t)
print(string)

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
File 2 :

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:
n =yield
t = (a*(n**2))+b
string = "Expression, "+str(a)+"*x^2 + "+str(b)+", with x being "+str(n)
+" equals "+str(t)
print(string)

File 3:

m
er as
co
def linear_equation(a, b):

eH w
while True:
n =yield

o.
t = (a*(n**2))+b rs e
string = "Expression, "+str(a)+"*x^2 + "+str(b)+", with x being "+str(n)
ou urc
+" equals "+str(t)
print(string)

# Define the coroutine function 'numberParser' below


o

def numberParser():
aC s

equation1 = linear_equation(3, 4)
v i y re

equation2 = linear_equation(2, -1)


# code to send the input number to both the linear equations
next(equation1)
equation1.send(6)
next(equation2)
ed d

equation2.send(6)
ar stu

def main(x):
n = numberParser()
#n.send(x)
sh is

=========================================================
Th

Handson # 10 Descriptors

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

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
def __init__(self, initial_f):
self.fahrenheit = initial_f

m
er as
co
eH w
o.
rs e
ou urc
o
aC s
v i y re
ed d
ar stu
sh is
Th

This study source was downloaded by 100000824981070 from CourseHero.com on 07-04-2021 19:21:17 GMT -05:00

https://www.coursehero.com/file/67036952/Fresco-code-Python-Application-programming/
Powered by TCPDF (www.tcpdf.org)

You might also like