Docsity

CPSC 121 (Fall 2012) Lecture Notes: Quiz 5, Range Loops, Nested Loops, Study notes of Computer Science

Partial preview of the text

Download CPSC 121 (Fall 2012) Lecture Notes: Quiz 5, Range Loops, Nested Loops and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Quiz 5
  • More on range loops
  • Nested loops

Reading

  • Ch 11 and 12

Warm up

Exercise: Write a print reverse function that prints each element in a list in reverse order, but does not use reverse. (Hint: use range.)

Answer:

def print_reverse(a_list): for i in range(len(a_list)-1, -1, -1): print(a_list[i])

Q: What is printed if we call print reverse([])? Why?

Nested loops

Since the body of a loop can contain any Python statements ...

  • We can define “nested” loops for i in range(5): for j in range(4): print("i =", i, ", j =", j)

Q: What does this print? i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 0, j = 3 i = 1, j = 0 i = 1, j = 1 ... i = 4, j = 3

Note the “inner” loop is just a statement: for i in range(5): statement 1

And multiple statements can be in for-loop body: for i in range(5): for j in range(4): print("inner-loop iteration") print("inner-loop finished")

Q: What does this print?