Introduction to Python

davidbpython.com




In-Class Exercises, 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'
Expected Output:
Hello  there   treasured  Python friends'
California,31,39.51,3200
 
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'
Expected Output:
['Hello', 'there', 'treasured', 'Python', 'friends.']
['California', '31', '39.51', '3200']
 
Ex. 3.3 Slice a string. Slice the 4-digit year, 2-digit month and 2-digit day of 'fw_line'.
fw_line = 'DATE20150903'
 
Ex. 3.4 Use variables to slice the 4-digit year of 'fw_line'.
fw_line = 'DATE20150903'

start_index = 4
end_index = 8
 

LISTS

 
Ex. 3.5 List operations.

Perform the noted operations on list 'x'

x = ['hello', 'there', 'Python', 'friends']


# print the type of the list (use type())



# show the length of the list (use len())



# access and print the first item of the list (use list subscript)



# access and print the last item of the list (use negative subscript)



# use a variable index to print the last item
last_idx = -1



print()
Expected Output:
<class 'list'>
hello
friends
4
 

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'
Expected Output:
39.51
 
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'
Expected Output:
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.

dickens = 'It was  the best of times, it was the worst of times.'
Expected Output:
best
times
 
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.'
Expected Output:
11
 
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..."
Expected Output:
In
more
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'
Expected Output:
000095327
 

LOOPING

 
Ex. 3.12 Loop through and print each individual item in the list (use 'for')
x = ['What', 'do', 'you', 'think?']
Expected Output:
What
do
you
think?
 
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]
Expected Output:
4
6.33
 

FILES

 
Ex. 3.14 File operations.

Perform the below operations:

filename = '../pyku.txt'



# open file 'pyku.txt' and assign to variable 'fh' (use open())



# print the type of variable 'fh'


print()

# iterate over the variable 'fh' with 'for' and print each line in the file
Expected Output:
<class '_io.TextIOWrapper'>

We're out of gouda.

This parrot has ceased to be.

Spam, spam, spam, spam, spam.
 
Ex. 3.15 Using 'with' context to open files.

Again open pyku.txt for reading, and loop through and print each line, but use a 'with' block to open the file.

filename = '../pyku.txt'
Expected Output:
We're out of gouda.

This parrot has ceased to be.

Spam, spam, spam, spam, spam.
 

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. You should see a blank line between each printed line (this is the newline character).

filename = '../pyku.txt'
Expected Output:
We're all out of gouda.

This parrot has ceased to be.

Spam, spam, spam, spam, spam.
 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
We're all out of gouda.
This parrot has ceased to be.
Spam, spam, spam, spam, spam.
 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
3
 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
Alpha
Beta
Gamma
Delta
Epsilon
 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
0701
0702
0103
0104
0201
0202
0103
0104
0105
 
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'

fh = open(fname)

for line in fh:
    # your code here
Expected Output:
6
2
0
8
4
 
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'

fh = open(name)

for line in fh:
    # your code here
Expected Output:
6.3
2.1
2.2
4.8
3.6
 
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'

fh = open(fname)

for line in fh:
    line = line.rstrip()
    # your code here
Expected Output:
9.0

Note that if you see a very long (and tiny) remainder, to use the round() function to round to one decimal place.

 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
Hipster's
Dothraki Fashions
The Clothiers
 
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'

fh = open(filename)

for line in fh:
    # your code here
Expected Output:
0.015
0.011
0.022
0.018
 
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'

fh = open(fname)

for line in fh:
    line = line.rstrip()
Expected Output:
265.4
 

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'
fh = open(filename)

counter = 0
summer = 0.0

# 1. loop through file line-by-line; strip and print each line

    # 2. count each iteration; print count at end

    # 3. split each line on a comma; print each split line

    # 4. subscript float value from split list; print each subscripted value

    # 5. convert float value (a string) to float

    # 6. sum up float values; print sum after loop ends

    # 7. adding a horizontal bar to separate iterations
    print('------------------------------')


# close file


# print sum and count
Expected Output:
Haddad's,PA,239.50

["Haddad's", 'PA', '239.50\n']
239.50
------------------------------
Westfield,NJ,53.90

['Westfield', 'NJ', '53.90\n']
53.90
------------------------------
The Store,NJ,211.50

['The Store', 'NJ', '211.50\n']
211.50
------------------------------
Hipster's,NY,11.98

["Hipster's", 'NY', '11.98\n']
11.98
------------------------------
Dothraki Fashions,NY,5.98

['Dothraki Fashions', 'NY', '5.98\n']
5.98
------------------------------
Awful's,PA,23.95

["Awful's", 'PA', '23.95\n']
23.95
------------------------------
The Clothiers,NY,115.20

['The Clothiers', 'NY', '115.20\n']
115.20
------------------------------
7
662.0100000000001
 
[pr]