Exercises for Lesson 11

Back to Lesson 11

Exercise 1: break versus continue

What values are printed in each of the following loops?

for i in range(10):
    if i == 3:
        break
    print(i)

for i in range(10):
    if i == 3:
        continue
    print(i)

Back to Lesson 11

Exercise 2: Compound Boolean expressions

Predict the result of each of the following expressions.

x = 4
y = 2

(a)  x > 0 and y < 5

(b)  x == 4 and False

(c)  (not x == 3) and (not y <= 2)

(d)  x == 0 or (x > 1 and y != 14)

Exercise 3: Simplifying Boolean expressions with truth tables

We’ll write a truth table for the following expression:

a and (not b or a)

To build it incrementally, you should use these columns:

  • a
  • b
  • not b
  • not b or a
  • a and (not b or a)

Once you are done, verify the full expression is equivalent to the expression a.

Back to Lesson 11

Exercise 4: More truth tables

Write truth tables for the following expressions.

(a)  a and (not b)

(b)  (a and b) or (not a and not b)

(c)  not (a and b)

Exercise 5: More practice with simplification

Part a: more truth tables

Write truth tables for the following expressions.

(i)  (a or b) and (not a or b)

(ii)  not (a or (b and a))

Part b: simplification via truth table

Use your truth tables from Part (a) to verify the following simplified expressions are equivalent to the original expressions.

(i) b

(ii) not a

Back to Lesson 11

Exercise 6: Playing around with strings

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

s1 = "apple"
s2 = "banana!"

Exercise 6a: from expression to output

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

a) "I would like a " + s2

b) 2 * s1 + s2

c) s2[2:4]

d) s1[0] + s2[-2:] + s2[-1]

e) s2[len(s1)]

Exercise 6b: 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 6c: looping through strings

Show the output that would be generated by each of the following program fragments:

a) for ch in "zebra":
       print(ch)

b) for ch in "fish":
       print("#" + ch * 3 + " " + ch)

Back to Lesson 11

Exercise 7: Playing with chr and ord

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

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

Back to Lesson 11