Computer Science 15-110, Spring 2011
Class Notes: Code Tracing Practice


Code Tracing Practice

Code tracing just traces output, without higher-level reasoning over code.

Predict the output for each of these code snippets.
  1. # while loop
    def f():
    x = 10
    y = 100
    print "before loop:", x, ",", y
    while (x < y/2):
    x += 1
    y /= 2
    print "in loop:", x, ",", y
    print "after loop:", x, ",", y
    f()
  2. # for loop
    def f():
    x = 1
    y = 2
    print "before loop:", x, ",", y
    for z in range(y,y+3):
    x += z
    y -= x
    print "in loop:", x, ",", y
    print "after loop:", x, ",", y
    f()
  3. # loop and conditional
    def f():
    x = 1
    y = 2
    print "before loop:", x, ",", y
    for z in range(30):
    if (z%10 == x%10):
    y += 4
    print "in loop, in if:", [x,y,z]
    elif (z%10 == y):
    x *= 3
    print "in loop, in elif:", [x,y,z]
    print "after loop:", [x,y,z]
    f()
  4. # nested loop
    def f():
    w = 1
    x = 2
    print "before loop:", w, ",", x
    for y in range(3):
    for z in range(-5, 5):
    if (y+z == x+w):
    w += x
    x += 1
    print "in loop, in if:", [w,x,y,z]
    print "after inner loop:", [w,x,y,z]
    print "after outer loop:", [w,x,y,z]
    f()
  5. # function calls
    def f(x, y):
    x = y/2
    y = x/2
    return x + y

    def g(y, x):
    return f(x, y)

    def h():
    x = 13
    y = 42
    print f(x,y)
    print g(x,y)
    print g(f(x,y), g(x,y))

    h()