Exercises for Lesson 5

Back to Lesson 5

Exercise 0: Playing with chr and ord

Show the output that would be generated by the following program fragment:

for ch in "fish":
    newval = ord(ch) + 4
    mystery = chr(newval)
    print(mystery)

Back to Lesson 5

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) s1.index('a')

b) s2.split('n')

c) len(s2)

d) 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) 4

Back to Lesson 5

Exercise 2: Basic list operations

For this exercise, we’ll use the following statements:

numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]

Predict the result of evaluating each of the following list expressions.

a) numbers[-1]

b) words[1:4]

c) words[1] + words[2]

d) len(numbers)

e) numbers + words

f) 2 * numbers + words

g) for word in words:
       print(word[:3])

Exercise 3: Going backwards

Write a program to print a sequence of words in reverse order. You cannot use slicing or the existing reverse list method. (Hint: you should use split to turn the provided string into a list, and use the accumulator pattern to build the resulting list in reversed order. Remember our loop in Lesson 4 reversing a single string?)

Here is an example interaction:

Please enter a sequence of words, separated by spaces: apple banana cat dog elephant fish

The sequence reversed:
fish elephant dog cat banana apple

Back to Lesson 5

Exercise 4: For-loop patterns

Write a for loop using the variables numbers and words to generate each output. Think about whether you need the element and/or its index for each loop.

numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]

a) ae
   ba
   ct
   dg
   et

b) 0 apple
   1 banana
   2 cat
   3 dog
   4 elephant

c) 3
    1
     4
      1
       5

Back to Lesson 5