Exercises for Lesson 9
Exercise 1: Working with strings
For this exercise, we’ll use the following statements:
s1 = "apple"
s2 = "banana!"Exercise 1a: from expression to output
Predict the result of evaluating each of the following string expressions.
a) s2.split('n')
b) len(s2)
c) s1[8 % len(s1)]Exercise 1b: from output to expression
Build a Python expression that could construct each of the following results by performing string operations on s1 and s2.
s1 = "apple"
s2 = "banana!"
a) ['b', 'n', 'n', '!']
b) ['a', '', 'le']
c) ['a', 'le']Exercise 2: Reading numbers from a CSV file
Assume you have a file nums.txt with one number on each line, like this:
111
42
2025
10
3In fact, copy these five lines, and create a new file called nums.txt where you can save them.
Exercise 2a: How files are stored
First, think about how the file above is stored in the computer. If you read in the whole file, what single string would you get?
Exericse 2b: Parsing numbers
Now, write a program to read in all of the numbers in this file and print out the following:
- the smallest number
- the biggest number
- how many numbers there were
When you run your program, your output should look like this:
Smallest: 3
Largest: 2025
Count: 5Exercise 3: Reading multiple values from a CSV file
Assume you have a file names.csv with the following contents:
Lulu,12
Hobbes,12
Cheddar,0Write a program that reads in the file and prints a message for each user:
>>> main()
Hi Lulu, you are 12 year(s) old.
Hi Hobbes, you are 12 year(s) old.
Hi Cheddar, you are 0 year(s) old.If you have time, think about how you can tailor the message to print “year” or “years”, as appropriate.
Exercise 4: Drawing earthquakes from a CSV file
If you have time, try to change our plotQuakes.py program to read in its data from the file earthquakes.csv, rather than having a hard-coded list. Can you get it to draw the same output?