


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Today ...
Reading
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?
Since the body of a loop can contain any Python statements ...
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?