Overview

We’ll be exploring a couple more useful building blocks today: definite loops (for) and changing the value of a variable.

Basic Learning Objectives

Before class, you should be able to:

  • Change an existing variable
  • Iterate a certain number of times using range
  • Explain what the accumulator pattern is

Advanced Learning Objectives

After class, you should be able to:

  • Predict what value a variable will have at the end of a program, especially when the program uses and changes multiple variables
  • Draw reference diagrams to show what is happening with a variable in a program, especially when the variable is changed
  • Use several variables in a program to solve a problem
  • Solve a problem using the accumulator pattern

Readings

You should complete the following Runestone readings and embedded checks. Note that we are jumping ahead in the book a bit to be able to do some cool stuff sooner, so don’t worry about some unfamiliar things showing up in the readings in Chapter 7, we’ll get to it all soon!

Checks

Submit answers to the following on Moodle. For the diagrams, feel free to draw on paper and upload.

  • (Checkpoint 2.12.3) After the following statements, what are the values of x and y?
      x = 15
      y = x
      x = 22
    
  • Draw the “reference” diagram (i.e. memory diagram) of the following code:
      a = 3
      b = 7
      a = a + b
      b = 5
    
  • (Checkpoint 7.5.2) Consider the following code:
      nums = "123456789"
      for w in nums:
          accum = 0
          accum = accum + w
      print(accum)
    

    What happens if you put the initialization of accum inside the for loop as the first instruction in the loop?

  • Write code using range and for to accumulate the sum of numbers from 5 to 43. You can test your code below and then copy your solution to Moodle: