Lab 6: Knowledge Check

These questions check your knowledge of concepts from this lab. Use the button at the bottom to show your answers once you've attempted them.

  1. Which of the following are useful techniques for debugging issues with a loop? (pick one or more)
    1. Add a print statement on the first line of the loop to see how many times it iterates.
    2. Add a print statement within the loop to print the values of key variables or expressions.
    3. Use the Thonny debugger to step through the loop, using breakpoints to fast-forward to each iteration.
  2. What should you do if code containing a loop keeps running for a long time? (pick one or more)
    1. Let it run for at least 15 minutes. It will eventually stop.
    2. Stop it, using control-C, or the stop button in Thonny/Jupyter.
    3. Add print statements so that you can see more about what it is doing.
    4. Change any for loops into while loops to make sure they will stop.
    5. Make sure to clear the output in Jupyter so that the notebook doesn't have loading issues the next time you open it.
  3. If we run the following code, what is the sequence of numbers that gets printed (ignoring formatting)?
    x = 0
    while x < 7:
        x += 2
        print(x)
        x += 2
        print(x)
        x += 2
    print(x)

    1. 2, 4, 6
    2. 2, 4, 6, 8
    3. 2, 4, 8
    4. 2, 4, 8, 10
    5. 2, 4, 8, 10, 12
    6. 2, 4, 8, 10, 14, 16, 18
  4. If we run the following code, what gets printed?
    s = 'hello'
    r = ''
    for i in range(len(s)):
        r = s[i] + r
    
    print(r)

    1. olleh
    2. lleh
    3. hello
    4. hell

Table of Contents