Exercises for Lesson 4
Exercise 1: Playing around 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) "I would like a " + s2
b) 3 * s1 + s2
c) s2[2:4]
d) s1[3] + s2[3:] + s2[-1]
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) "nana"
b) "apple banana! apple banana! apple banana!"
Exercise 2: Looping through strings
Show the output that would be generated by each of the following program fragments:
a) for ch in "banana":
print(ch)
b) for ch in "apple":
print("#" + ch * 3 + " " + ch)
Exercise 3: Looping through strings, part 2
Show the output that would be generated by the following program fragment:
msg = ""
for ch in "banana":
msg = msg + chr(ord(ch) + 1)
print(msg)