Introduction to Python
davidbpython.com
In-Class Exercises, Session 11
|
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
|
FUNCTIONS: REVIEW |
|
| Ex. 11.1 | Write a function that takes an argument and returns a value. |
|
Function doubleit() takes one argument and returns its argument value doubled. |
|
# your def here
# you must not print inside the function
# you must not take input() inside the function
# you must not use 'y' inside the function
y = 5
dy = doubleit(y) # calling 'doubleit()', expecting one return value
print(dy) # 10
|
|
| Ex. 11.2 | Write another function that takes an argument and returns a value. |
|
Write a function get_greeting() that takes one string argument (a name) and returns "Hello, " followed by the name and an exclamation point. |
|
# your def here
# you must not print inside the function
# you must not take input() inside the function
# you must not use 'x' or 'y' inside the function
x = 'World'
y = 'Guido'
# here, call get_greeting() with 'x' as argument
# make sure to expect a return value
# the return value should be 'Hello, World!'
# here, call get_greeting() with 'y' as argument
# make sure to expect a return value
# the return value should be 'Hello, Guido!'
|
|
| Ex. 11.3 | Write a function that takes two arguments and returns one value. |
|
Define function multiplyem() that takes two numbers, multiplies them together, and returns the product. |
|
# your def here
# you must not print inside the function
# you must not take input() inside the function
# you must not use 'a' or 'b' inside the function
a = 5
b = 10
# here, call multiplyem() with 'a' and 'b' as arguments
# make sure to expect a return value
# the return value should be 50
|
|
| Ex. 11.4 | Write a function that takes one argument and returns two values. |
|
Function mul_and_div takes an int argument and returns the value doubled and the value halved (/2) |
|
# your def here
# you must not print inside the function
# you must not take input() inside the function
# you must not use 'a' inside the function
a = 5
d, h = mul_and_div(a)
print(d) # 10
print(h) # 2.5
|
|
| Ex. 11.5 | Write a function that returns None (without explicitly returning it). |
|
Write function greet(), which simply prints 'Hello, world!'. Printing x should show None. |
|
# make sure your function does not attempt to return anything
x = greet()
print(x) # None
|
|
| Ex. 11.6 | Demonstration: remove a return statement and note the value. |
|
The below function returns the sum of its arguments. First run the program and note the printed value, then remove the return statement to see the printed value. |
|
def get_sum(val1, val2):
valsum = val1 + val2
return valsum
r = get_sum(5, 10)
print(r)
|
|
| Ex. 11.7 | Write a function that takes one positional (required) argument and one keyword (optional) argument. |
|
Define function mul, which should take a required integer argument and an optional integer argument (keyword 'multiplier', with default 1. If the optional arg is not passed, it should default to 1 (so that the argument value is multiplied by 1 and thus returned unchanged). |
|
# your def here
a = 5
b = mul(a, multiplier=3) # int, 15
c = mul(a) # int, 5
|
|
| Ex. 11.8 | Write a function that takes two positional (required) arguments and one keyword (optional) argument. |
|
Define function get_field, which should take a required string argument, a required integer argument and an optional string argument (keyword 'sep', with default ','. The function takes a CSV line and an integer index. It splits the line on the separator and returns the field indicated by the integer -- see examples below. If the optional arg is not passed, it should default to ','. |
|
# your def here
v1 = get_field('hey:you:stop', 0, sep=':') # 'hey' (splits on the colon, then returns 1st item)
v2 = get_field('this,that,other', 1) # 'that' (splits on the default comma, then returns 2nd item)
|
|
|
FUNCTIONS: VARIABLE SCOPES |
|
| Ex. 11.9 | Explore function scoping. |
|
Call this function, then attempt to print lvar after calling the function. Is lvar available outside the function? |
|
def do(arg):
lvar = arg * 2
return lvar
a = do(5)
print(a)
|
|
| Ex. 11.10 | Explore global variables inside functions. |
|
Replace 2 with gvar inside the function, then call the function. Is gvar available inside the function? |
|
gvar = 2
def do(arg):
lvar = arg * 2
return lvar
a = do(5)
print(a)
|
|
| Ex. 11.11 | Identify local and global variables. |
|
Identify the 3 local variables, 3 global variables and 2 builtin variables in the below code: |
|
filename = 'pyku.txt'
def get_text(fname):
fh = open(fname)
text = fh.read()
return text
txt = get_text(filename)
print(txt)
|
|
|
RAISE STATEMENT |
|
| Ex. 11.12 | Raise an exception. Test to see if the user's input matches one of the values in the valid_choices list (use if uchoice not in valid_choices). If not, raise a ValueError exception with a descriptive error message. |
def validate_choice(uchoice):
valid_choices = ['run', 'stop', 'rewind']
if uchoice not in valid_choices:
# your code here
validate_choice('run') # should have no visible effect - function did not raise
validate_choice('fastforward') # should raise ValueError with a message
|
|
| Ex. 11.13 | Detect object type and raise TypeError. Use the isinstance() function to see if the argument to this function is an integer. If it isn't, raise your own TypeError exception with a descriptive error message. |
def doubleit(arg):
if not isinstance(arg, int):
# your code here
return arg * 2
x = doubleit('5')
|
|
|
LAB 1 |
|
| Ex. 11.14 | Write a function that validates its argument. |
|
Define function make_case(), which takes two arguments: text, a string to be modified, and case a string that must be either 'upper' or 'lower'. If case is not one of these, the function should raise a ValueError exception. Then based on the case argument, return the string uppercased or lowercased. |
|
# your function def here
greeting = 'Hello.'
x = make_case(greeting, 'upper') # str, 'HELLO.'
print(x)
y = make_case(greeting, 'lower') # str, 'hello.'
print(y)
z = make_case(greeting, 'middle') # ValueError: "middle" is not a valid argument:
# must be "upper" or "lower"
|
|
Expected Output:
HELLO. hello. ValueError: "middle" is not a valid argument: must be "upper" or "lower" |
|
| Ex. 11.15 | Write a function with an optional argument. |
|
Modify the above function so that the 2nd argument is optional, with default 'upper'. Make sure it behaves as shown when called as shown below. |
|
# your function def here
greeting = 'Hello.'
a = make_case(greeting, case='lower') # str, 'hello.'
print(a)
b = make_case(greeting, case='upper') # str, 'HELLO.'
print(b)
c = make_case(greeting) # str, 'HELLO.'
print(c)
d = make_case(greeting, case='title') # ValueError: "title" is not a valid argument:
print(d) # must be "upper" or "lower"
|
|
Expected Output:
hello. HELLO. HELLO. ValueError: "title" is not a valid argument: must be "upper" or "lower" |
|
| Ex. 11.16 | Write a function with both positional and optional arguments. |
|
Write function temp_convert() that takes one required argument temp, a temperature value, and an optional argument scale=, which must be 'C' or 'F', and a default value of 'C'. If scale is not 'C' or 'F', the function raises a ValueError. Formula for F->C: (x - 32) * 5/9 Formula for C->F: (x * 9/5) + 32 Make sure the function behaves as shown below with the below arguments. |
|
# your function def here
c = temp_convert(212, scale='C') # 100
print(c)
f = temp_convert(0, scale='F') # 32
print(f)
cc = temp_convert(32) # 0
print(cc)
ff = temp_convert(-1, scale='Fahrenheit') # ValueError: "Fahrenheit" is not a
# valid argument: must be "C" or "F"
print(ff)
|
|
Expected Output:
100 32 0 ValueError: "Fahrenheit" is not a valid argument: must be "C" or "F" |
|
| Ex. 11.17 | Write a function that returns multiple values. |
|
Define function name_split(), which takes a single string and attempts to split it on whitespace into 2 or 3 items. If there are more than 3 or fewer than 2 items, it raises a ValueError with a descriptive message. If there are three items, it returns them; if there are two items, it returns the first item, None, and the second item. Make sure the function return values are as shown below. |
|
# your function def here
first, second, third = name_split('George Patrick Flanahanahan')
print(first, second, third) # 'George', 'Patrick', 'Flanahanahan'
fname, sname, tname = name_split('Aimee Vonda')
print(fname, sname, tname) # 'Aimee', None, 'Vonda'
fn, sn, tn = name_split('Gimpy P. W. Simpson')
print(fn, sn, tn) # ValueError: must be 2 or 3 words in name
|
|
Expected Output:
George Patrick Flanahanahan Aimee None Vonda ValueError: must be 2 or 3 words in name |
|
| Ex. 11.18 | Identify global and local variables. |
|
Identify the global and local names in the below code. There are 3 local and 4 global names to be identified. |
|
a = 5
def do(c, d):
e = c * d
return e
b = 100
x = do(a, b) # 500
print(x)
|
|
|
READING FROM MODULES |
|
| Ex. 11.19 | Import a module and use its variables. Import module 'mymod' and print one of its variables. |
# your import and code here
|
|
| Ex. 11.20 | Import a module as a different name and use its variables. Perform the same as above but import the module as 'mm'. Again, print one of the varibles from mymod.py. |
# your import and code here
|
|
| Ex. 11.21 | Import a variable from a module into the program's namespace. |
|
Perform the same as above but import a variable from 'mymod.py' directly into this program's namespace. You should be able to print this variable without prepending the name with mymod or mm. Again, print one of the varibles. |
|
# your import and code here
|
|
|
USEFUL MODULES |
|
| Ex. 11.22 | Exploring documentation: math. |
|
Do a google search for python documentation. At the documentation page, choose Library Reference. Note all the many modules listed on this page -- these are the modules that are included in the Python standard distribution -- the Python install provided by python.org. Find the math module. Below, see if you can import math and then make use of one of the functions in the module. |
|
| Ex. 11.23 | Featured module: zipfile. |
import zipfile as zp
myzip = zp.ZipFile('myzip.zip', 'w')
# add names of files in the current directory
myzip.write() # write 1st filename here
myzip.write() # write 2nd filename here
myzip.close()
print('done')
|
|
|
After running the above, check the session files directory -- you should see a new .zip file added. |
|
| Ex. 11.24 | Featured module: time. |
import time
secs = time.time()
# print(time.ctime(secs))
# print(time.localtime(secs))
# time.sleep(5)
|
|
| Ex. 11.25 | Featured module: datetime. |
import datetime as dt
# mydate = dt.date(2019, 9, 3)
# mydate = dt.date.today()
# mydatetime = dt.datetime(2019, 9, 3, 12, 5, 30)
# mydatetime = dt.datetime.now()
#secs = time.time()
#time_elements = time.localtime(secs)
#print(time_elements)
# myinterval = dt.timedelta(days=3, seconds=120)
# newdate = mydate + myinterval
# print(newdate)
# print(newdate.strftime('%Y-%m-%d'))
# dt.datetime.strptime('2019-03-03', '%Y-%m-%d')
|
|
| Ex. 11.26 | Featured module: random. |
import random
myfloat = random.random()
# num = random.randint(10)
# num = random.randint(3,5)
# x = ['a', 'b', 'c']
# choice = random.choice(x)
|
|
| Ex. 11.27 | Featured module: csv. |
import csv
fh = open('dated_file.csv')
reader = csv.reader(fh)
for row in reader:
print(row)
fh.close()
# wfh = open('newfile.csv', 'w', newline='')
# writer = csv.writer(wfh)
# writer.writerow(['a', 'b', 'c'])
# wfh.close()
# Again, please be advised that you will not see writes to a file
# until you close the file with fh.close() or until the program
# ends execution.
|
|
| Ex. 11.28 | Featured module: openpyxl. |
|
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import openpyxl as ox
# read an Excel workbook from a file
# read_only=True will limit your actions to reading
wb = ox.load_workbook('revenue.xlsx', read_only=True)
# show list of sheets within the workbook
print(wb.sheetnames)
# ['transactions']
# access a single sheet within the workbook
ws = wb['transactions']
# loop through the entire worksheet and look at each row
for row in ws.iter_rows():
# subscript out two fields from the row
col1 = row[0].value
col2 = row[1].value
# to skip rows (for example, headers) you can use min_row= argument:
for row in ws.iter_rows(min_row=2):
# subscript out two fields from the row
col1 = row[0].value
col2 = row[1].value
# note that older versions of openpyxl may use the skip_rows= argument instead of min_row=.
# access one cell by Excel cellname
c = ws['A2'] # 'cell' object
print(c.value) # the value in the cell
print(ws['B2'].value) # access value in one statement
|
|
| Ex. 11.29 | Featured module: sqlite3. |
import sqlite3
conn = sqlite3.connect('mydatabase.db')
cur = conn.cursor()
cur.execute("CREATE TABLE mytable (name TEXT, years INT, balance FLOAT)")
cur.execute("INSERT INTO mytable VALUES ('Joe', 23, 23.9)")
cur.execute("INSERT INTO mytable VALUES ('Marie', 19, 7.95)")
cur.execute("INSERT INTO mytable VALUES ('Zoe', 29, 17.5)")
conn.commit()
cur = conn.cursor()
rs = cur.execute('SELECT * FROM mytable')
for row in rs:
print(row)
|
|
| Ex. 11.30 | Featured module: pandas data acquisition. |
|
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import pandas as pd
import sqlite3
df = pd.read_csv('dated_file.csv')
# write DataFrame to excel
#df.to_excel('dated_file.xls')
# read from database through query
# conn = sqlite3.connect('testdb.db')
# df = pd.read_sql('SELECT * FROM test', conn)
|
|
| Ex. 11.31 | pandas data management. |
df = pd.read_csv('dated_file.csv')
# sum, average, etc. a column
# create a new column
# select rows thru a filter
# groupby aggregation
|
|
| Ex. 11.32 | pandas visualization. |
# groupby bar chart
# weather temp line chart
|
|
| Ex. 11.33 | Featured module: bs4. |
|
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import bs4
fh = open('dormouse.html')
text = fh.read()
page = bs4.BeautifulSoup(text, 'html.parser')
print(page.title)
fh.close()
|
|
| Ex. 11.34 | Featured module: requests. |
|
(Note: if not using Anaconda Python, bs4 must be installed separately.) |
|
import requests
import bs4
response = requests.get('http://www.nytimes.com')
page = bs4.BeautifulSoup(response.text, 'html.parser')
print(page.title)
|
|
| Ex. 11.35 | Featured module: re. |
import re
line = 'a phone number: 213-298-1990'
matchobj = re.search(r'(\d\d\d)\-(\d\d\d)\-(\d\d\d\d)', line)
print(matchobj.group(1))
|
|
| Ex. 11.36 | Featured module: subprocess. |
import subprocess
subprocess.call(['python', 'hello.py'])
# out = subprocess.check_output(['python', 'hello.py')
|
|
| Ex. 11.37 | Featured module: textwrap. |
import textwrap
text = ("This is some really long text that we would like to wrap. "
"Wouldn't you know it, there's a module for that! ")
items = textwrap.wrap(text, 10)
print('\n'.join(items))
|
|