Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 3
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
NOTE THAT the data files read from these exercises is located in the "parent" directory. Thus any filename in these exercises should be preceded with ../. (If you create a script in the same directory as the data file, this would not be necessary.) |
|
STRINGS |
|
Ex. 3.1 | .rstrip() a string of a charactrer or whitespace. Strip the sentence of the period; strip the csv line of the newline character. Print each. |
sentence = 'Hello there treasured Python friends.'
csv_line = 'California,31,39.51,3200\n'
stripsen = sentence.rstrip('.')
stripcsv = csv_line.rstrip()
print(stripsen)
print(stripcsv)
|
|
Ex. 3.2 | .split() a string on a character or on whitespace. Split the sentence into words; split the CSV line into fields. Print each. |
sentence = 'Hello there treasured Python friends'
csv_line = 'California,31,39.51,3200'
words = sentence.split()
fields = csv_line.split(',')
print(words)
print(fields)
|
|
Ex. 3.3 | Slice a string. Slice the 4-digit year, 2-digit month and 2-digit day of 'fw_line'. |
fw_line = 'DATE20150903'
year = fw_line[4:8]
month = fw_line[8:10]
day = fw_line[10:12]
|
|
Ex. 3.4 | Use variables to slice the 4-digit year of 'fw_line'. |
fw_line = 'DATE20150903'
start_index = 4
end_index = 8
year = fw_line[start_index:end_index]
|
|
LISTS |
|
Ex. 3.5 | List operations. |
Perform the noted operations on list 'x' |
|
x = ['hello', 'there', 'Python', 'friends'] # list, ['hello', ... ]
# print the type of the list (use type())
print(type(x)) # <class 'list'>
# access and print the first item of the list (use list subscript)
print(x[0]) # hello
# access and print the last item of the list (use negative subscript)
print(x[-1]) # friends
# use a variable index to print the last item
last_idx = -1
print(x[last_idx])
# show the length of the list (use len())
print(len(x)) # 4
print()
|
|
LAB 1 |
|
Ex. 3.6 | Print item from a delimited string. |
Select and print the 3rd value. Do not use a slice. |
|
delimited = 'New York,31,39.51,3200' # str, 'New York,31...'
items = delimited.split(',') # list, ['New York', '31' ... ]
fval = items[2] # str, '39.51'
print(fval)
|
|
Ex. 3.7 | Select number from a delimited string, use as number. |
Select the 2nd value, then double it to 62. Do not use a slice. |
|
delimited = 'New York,31,39.51,3200' # str, 'New York,31,39...'
items = delimited.split(',') # list, ['New York', '31' ... ]
ival = items[1] # str, '31'
iival = int(ival) # int, 31
print(iival * 2) # 62
|
|
Ex. 3.8 | Print a word from a space-delimited string. |
Print the 4th word from dickens. Then print the last word with the trailing period stripped. Do not use a slice. |
|
dickens = 'It was the best of times, it was the worst of times.'#
words = dickens.split() # list, ['It', 'was', 'the', 'best', 'of', 'times,' ... ]
bw = words[3] # str, 'best'
tw = words[5] # str, 'times,'
stw = tw.rstrip(',') # str, 'times'
print(bw)
print(stw)
|
|
Ex. 3.9 | Determine number of words in a string. |
In just two additional statements (not including printing), show the number of words in the string. |
|
swanns_way = 'For a long time I used to go to bed early.' # str, 'For a ...'
words = swanns_way.split() # list, ['For', 'a', 'long', 'time' ...]
print(len(words))
|
|
Ex. 3.10 | Show selected words from a string. |
Print the 1st word in the setence, the 5th word in the sentence, and the last word in the sentence. |
|
gatsby = "In my younger and more vulnerable years my father gave me some advice..." # str
words = gatsby.split() # list, ['In', 'my', 'younger', 'and' ...]
print(words[0]) # str, 'In'
print(words[4]) # str, 'more'
print(words[-1]) # str, 'advice...'
|
|
Ex. 3.11 | Slice part of a string. |
Print the numeric SKU value (the 9 digits after SKU only, not the 8) from serial. |
|
serial = '#SKU000095327MRCOFFEE8CUPCAPUC'
sn = serial[4:13] # str, '000095327'
print(sn)
|
|
LOOPING |
|
Ex. 3.12 | Loop through and print each individual item in the list (use 'for') |
x = ['What', 'do', 'you', 'think?']
for item in x: # str, 'hello' (initial value)
print(item)
|
|
Ex. 3.13 | List iteration and summary. |
Use 'for' to loop through list 'xval' and count the number of iterations, then extend it to also sum up the values. Print the sum and the count. |
|
xval = [3.9, 0.3, 2.1, 0.03] # list, [3.9, 0.3, 2.1, 0.03]
lcount = 0 # int, 0
lsum = 0.0 # float, 0.0
for val in xval: # int, 3.9 (initial value)
lcount = lcount + 1 # int, 1
lsum = lsum + val # float, 3.9
print(lcount)
print(lsum)
|
|
FILES |
|
Ex. 3.14 | File operations. |
Perform the below operations: |
|
filename = '../pyku.txt' # str, '../pyku.txt'
# open file 'pyku.txt' and assign to variable 'fh' (use open())
fh = open(filename) # 'file' object
# print the type of variable 'fh'
print(type(fh)) # <class '_io.TextIOWrapper'>
print()
# iterate over the variable 'fh' with 'for' and print each line in the file
for line in fh: # str, "We're out of gouda.\n" (initial value)
print(line)
|
|
Ex. 3.15 | Using 'with' context to open files. |
Again open pyku.txt for reading, and loop through and print each line, bu t use a 'with' block to open the file. |
|
filename = '../pyku.txt'
with open(filename) as fh:
for line in fh:
print(line)
|
|
LAB 2 |
|
Ex. 3.16 | Loop through a list. Loop through and print each individual item in the list (use 'for') |
mylist = ['a', 'b', 'c', 'd']
|
|
Expected Output:
a b c d |
|
Ex. 3.17 | Loop through a file and print each line. |
Loop through the file pyku.txt and print each line as you go. |
|
filename = '../pyku.txt' # str, '../pyku.txt'
fh = open(filename) # 'file' object
for line in fh: # str, "We're out of gouda.\n" (initial value)
print(line)
|
|
Ex. 3.18 | Loop through a file and strip each line. |
Loop through the file pyku.txt and strip and print each line as you go. You should see the lines printed without a blank line in between. |
|
filename = '../pyku.txt' # str, '../pyku.txt'
fh = open(filename) # 'file' object
for line in fh: # str, "We're out of gouda.\n" (initial value)
line = line.rstrip() # str, "We're out of gouda."
print(line)
|
|
Ex. 3.19 | Loop through file and count. |
Loop through the file pyku.txt and keep a running count of each line. Print the count at the end. |
|
filename = '../pyku.txt' # str, '..pyku.txt'
fh = open(filename) # 'file' object
counter = 0 # int, 0
for line in fh: # str, "We're out of gouda.\n" (initial value)
counter = counter + 1 # int, 1
print(counter)
|
|
The call to .rstrip() is not necessary because we're not using the end of the line. |
|
Ex. 3.20 | Loop through file and print one field. |
Loop through datafile.csv and print just the first field from each line. |
|
filename = '../datafile.csv' # str, '../datafile.csv'
fh = open(filename) # 'file' object
for line in fh: # str, 'Alpha,this,that,3,3.3\n' (initial value)
items = line.split(',') # list, ['Alpha', 'this', 'that' ...]
print(items[0]) # Alpha
|
|
The call to .rstrip() is not necessary because we're not using the end of the line. |
|
Ex. 3.21 | Loop through file and print one slice. |
Print the month and day from each line in FF_tiny.txt |
|
filename = '../FF_tiny.txt' # str, '../FF_tiny.txt'
fh = open(filename) # 'file' object
for line in fh: # str, '19260701 0.09 0.22 ... '
print(line[4:8]) # 0701
|
|
The call to .rstrip() is not necessary because we're not using the end of the line. |
|
Ex. 3.22 | Loop through file, isolate and double numeric value. |
Looping through datafile.csv, isolate the int value (4th field) and double it, printing each doubled value as you loop. |
|
fname = '../datafile.csv' # str, '../datafile.csv'
fh = open(fname) # 'file' object
for line in fh: # str, 'Alpha,this,that,3,3.3' (sample value)
items = line.split(',') # list, ['Alpha', 'this', 'that', '3' ...]
ival = int(items[3]) # int, 3
print(ival * 2) # 6
|
|
The call to .rstrip() is not necessary because we're not using the end of the line. |
|
Ex. 3.23 | Loop through file, isolate values and add together. |
Looping through datafile.csv, isolate the int value and float value (4th and 5th fields) and add them together, printing each summed value as you loop. |
|
name = '../datafile.csv' # str, '../datafile.csv'
fh = open(name) # 'file' object
for line in fh: # str, 'Alpha,this,that,3,3.3\n'
line = line.rstrip() # str, 'Alpha,this,that,3,3.3'
items = line.split(',') # list, ['Alpha', 'this' ... ]
ival = items[3] # str, '3'
fval = items[4] # str, '3.3'
sval = int(ival) + float(fval) # float, 6.3
print(sval)
|
|
Ex. 3.24 | Loop through file and sum up values in column. |
Looping through datafile.csv, sum up the last column of float values. Print the sum at the end. |
|
fname = '../datafile.csv' # str, '../datafile.csv'
fh = open(fname) # 'file' object
fsum = 0.0 # float, 0.0
for line in fh: # str, 'Alpha,this,that,3,3.3\n'
line = line.rstrip() # str, 'Alpha,this,that,3,3.3'
items = line.split(',') # list, ['Alpha', 'this' ... ]
fval = float(items[-1]) # str, '3.3'
fsum = fsum + fval # float, 3.3 (initial value)
print(fsum)
|
|
Ex. 3.25 | Loop through file and selectively print using split(). |
Looping through revenue.csv, print the company names for rows with 'NY' as the state. |
|
filename = '../revenue.csv' # str, '../revenue.csv'
fh = open(filename) # 'file' object
for line in fh: # str, "Haddad's,PA,239.50\n"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50\n']
company = items[0] # str, "Haddad's"
state = items[1] # str, 'PA'
if state == 'NY': # bool, False (initial value)
print(company)
|
|
Ex. 3.26 | Loop through file and selectively print using a slice. |
Looping through FF_tiny.txt, print the last float value on each line for the year 1927. |
|
filename = '../FF_tiny.txt' # str, '../FF_tiny.txt'
fh = open(filename) # 'file' object
for line in fh: # str, '19260701 0.09 0.22 0.30 0.009\n'
line = line.rstrip() # str, '19260701 0.09 0.22 0.30 0.009'
if line[0:4] == '1927': # bool, False (initial value)
items = line.split() # list, ['19270103', '0.97', '0.21' ... ]
print(items[-1]) # '0.015'
|
|
.rstrip() is required here because we're using the last value on the line. |
|
Ex. 3.27 | Loop through file and sum up selected value. |
Looping through revenue.csv, sum up the float value (3rd field) only for those rows from NJ (2nd field). |
|
fname = '../revenue.csv' # str, '../revenue.csv'
fh = open(fname) # 'file' object
fsum = 0.0 # float, 0.0
for line in fh: # str, "Haddad's,PA,239.50\n"
line = line.rstrip() # str, "Haddad's,PA,239.50"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50']
state = items[1] # str, 'PA'
if state == 'NJ': # bool, False (initial value)
fval = float(items[2]) # float, 239.5
fsum = fsum + fval # float, 239.5
print(fsum)
|
|
SUMMARY ALGORITHM; BUILDING FROM FILE |
|
Ex. 3.28 | File line iteration and summary. |
Use 'for' to loop through file 'revenue.csv' and count the number of iterations, then perform the operations noted below: test each step as you proceed. |
|
filename = '../revenue.csv' # str, '../revenue.csv'
fh = open(filename) # 'file' object
counter = 0 # int, 0
summer = 0.0 # float, 0.0
# 1. loop through file line-by-line; strip and print each line
for line in fh: # str, "Haddad's,PA,239.50\n" (initial value)
line = line.rstrip() # str, "Haddad's,PA,239.50"
print(line)
# 2. count each iteration; print count at end
counter = counter + 1 # int, 1
# 3. split each line on a comma; print each split line
items = line.split(',') # list, ["Haddad's", 'PA', '239.50']
print(items)
# 4. subscript float value from split list; print each subscript
fval = items[2] # str, '239.50'
print(fval)
# 5. convert float value (a string) to float
ffval = float(fval) # float, 239.5
# 6. sum up float values; print sum after loop ends
summer = summer + ffval # float, 239.5
# adding a horizontal bar to separate iterations
print('------------------------------')
# close file
fh.close()
# print sum and count
print(counter) # 7
print(summer) # 662.00000000000001
|
|