Variables

 Zoom Name:
Video Introduction (8 minutes) <<--- Watch this video first, then

English IDE <<--- Click this link to write your test program here.

After you have experimented with variables and operators, click the Yellow Done button to continue.
Then come back here and click this  Next link to skip down to the next video.

If it's not a link yet, you might need to refresh your browser, or else click this button to call a mentor:

Or, if you are like me and prefer to read at your own pace instead of whatever pace set in some video, You can read the transcript (and probably come out ahead of the non-readers).
 

Video Transcript: Variables

By this time you should have mastered getting your steps in order -- we call that Sequence -- you can move things around on the screen and query the date -- that would be Input and Output -- and you can change what the computer does based on things not known when you wrote it -- the word is Conditional -- and you can make the computer do the same thing several times -- Iteration. You also have some experience doing Top-Down Design using Subroutines.

We have six concepts that cover all of computer programming, and you already know five of them.

There is only one more concept left to go and you will have everything you need. Actually, you already had it in the very first program you wrote, PBJ.

People manipulate stuff -- peanut butter, jam, bread, plates, ideas, colors, numbers -- you name it, if you have a name for it, you can manipulate it, and if it's not a physical object, then at least you can manipulate the name and/or the idea it represents.

Computer programs manipulate information: numbers, names, groups of names and numbers representing physical objects or just ideas. In other words, stuff. The information can be very simple, or very complex but it has to go somewhere, in your hand, on the counter, on a plate, in the air on the way to somewhere, in your head, somewhere. The computer has millions of places to put numbers and names representing ideas and things and stuff. We call those places variables, because what you put there can vary from time to time.

Think of a variable as a container, like a glass of milk or a cabinet. Steve prefers to think of boxes, maybe because we all put stuff into boxes in December, and then we put names on those boxes. Then later somebody opens a box with their name on it and takes the stuff out.

A computer variable is something like that gift box, except the name is not usually a person, but rather what you intend to do with the box, like "Sum" or maybe even some silly name like "whatever" -- but that's usually not such a good idea, because we want to remember what it's for, and a very large program can have a very large number of variables (boxes) and it's easy to forget. And the names are all different.

Let's say we have three boxes, and each one has a piece of paper in it, like this:

The computer program can look at whatever is written on the piece of paper in any particular box -- let's say the first box with the name "Begin" -- and if it's a number (in this case the number 2) it can do something with that number -- say add +4 to it -- or it can add the number on the paper in another box -- like the 3 in box "AddMe" -- or add several numbers, or multiply or subtract, whatever the programmer (that would be you) wants to do -- and then write the sum on the piece of paper in another box, say that blank paper in the "Sum" box, like this:
In the computer we always refer to the boxes by name, and we have special commands for changing what is written on the piece of paper, called its value. Some programming languages require you to tell the computer what the name of the box is before you can do anything else with it. Usually they also let you say what its value is (what is written on its piece of paper) at the same time. Here is an example in our English programming language:
1 box Begin is 2
2 box AddMe is 3
3 box Sum        {no value specified}
4 let Sum be Begin +4 + AddMe
5 print "the sum is " Sum


I used the English word "is" to describe what "is" initially in each of the boxes, and "be" (same verb, but future) to describe something that is going into a box. That's the way we would say it in natural English. For historical reasons (card punch machines didn't have a lot of special characters), most programming languages use the "=" symbol. This is consistent with the way you used it when you did grade-school math problems, like in the picture above: You add up these numbers (2+4+3), then put the answer after the equal symbol, except programmers do it right-to-left. After you get into algebra, they redefine the equal symbol to mean "These two values are always exactly equal" rather than as an operator telling you where to put the result of a calculation. Programmers want to do that "exactly equal" thing also, but much less often than they want to put a result somewhere. Some programming languages (like the "English" you are learning today) use the "=" symbol in both places, because there is never any confusion about which you want it to mean. Most programming languages were invented by mathematicians who are in the business of confusing people (and being confused), so they invented separate symbols for the two contexts. A few languages -- Java unfortunately is one of them -- do it the worst possible way, they have two different symbols that are easily mistyped (one for the other) and then they let you use the wrong symbol in either context without complaining, and only later you discover you have the wrong result, perhaps after your million-dollar rocket crashed into Venus -- which actually happened, except in that programming language you could trade off commas and periods to get wrong results. The computer should help you catch mistakes, not make them hard to find. But it is what it is.


Computer variables are so important, you need to get a deep visceral understanding of them before we proceed. So let's go back to the IDE to experiment. Click this button to open it in a new window, which you can position to one side or above or below the instructions in this page:

Don't forget to type in your Zoom name if it's not there already.

Type these five lines (above) into the empty program panel, then click Run. The first thing it does is turn the first line green and stop with some extra information below the program panel but above the Quick Reference, something like this:

English State: Line 1

Variables:

Begin = ' '
AddMe = ' '
Sum = ' '


The English computer has determined that you have three variables, but there is nothing in any of them before the first line executes (does whatever it tells the computer to do). When you click the blue Step button, the line number will advance to Line 2 and the second line becomes green. Also, whatever you told the computer to do in Line 1 will have been done, so you can see that the variable "Begin" now has the value 2, but the other two variables are still blank.

Step again and variable (box) "AddMe" will get its initial value 3. Step again and nothing changes except the Line number. The next time you click Step, the variable Sum is given a value 9. The last time you click Step, the value of Sum is printed in the output panel on the right and execution stops.

This is called a "Debugger" because it helps you to see the "bugs" (errors) in your program so you can remove them. The debugger cannot remove any errors (only you can know if they are errors or not), but often we don't understand what we told the computer to do, and seeing it execute step by stem usually helps. There's an "English State Info" button just below the debugger area which summarizes what the parts mean.

Continuing on, you could combine lines 3 and 4 (try it)

3 box Sum is Begin +4 + AddMe
5 print "the sum is " Sum
Do you understand what happened? This is very important for understanding how to write programs. If you are the least bit confused, click the MentorAlert button here:


Now it gets interesting. Add new line 6 (or 5 or 18, your line numbers are ignored by the computer, they are there for your convenience) and another print line:

6 let Sum be Sum-5
7 print "the new sum is " Sum
Before you run it, try to guess what it will print. Then run it and see.

You can click the green "Fast" button and then click the Run button over the program panel, and it will run at full speed instead of one step at a time. The Step mode is useful when you want to see what each line does. If you want to Step only for a few lines in the middle of your program (but Fast everywhere else), you can insert a "Pause" line just before you want to begin stepping, then click the green Fast button (either before or after you click Run) and it will run fast up until it gets to the Pause line, then you can Step it a few (or many) times, then resume at full speed by clicking Fast again.

There's a lot more to be said about variables, but it will be easier to understand when we do a real computer program with real numbers, not just a sandwich, but a four-function calculator like you can buy for a couple bucks at the Dollar store or use on your smart phone.
 

Experiments

In (speaking) English we really don't have the concept of a variable -- we have containers, boxes or glasses we can put things in or take them out, but (outside the school office) the idea of a whole bunch of boxes with names on them is not the way we think of the world. But it's an essential way to think about computer programs.

What about what's inside the boxes? Right now we have a simple piece of paper with a number written on it. Of course we could write anything we want on that piece of paper, a number, a name, even a color, or (as we saw above) nothing at all. The kitchen computer lets you put anything into a variable that you can type on the keyboard (but not multiple lines). When it's a number, you can do arithmetic on it and put the result back into a box, perhaps the same box, replacing what was previously there. If you typed something other than a number -- perhaps your name or a line from a song -- then obviously you can't do any math with it, but you can put pieces of text together or grab out chunks to put with other chunks. We will do some of that later.

If you want to put a number into a variable (I mean box), you just do it like we did above.

If you want to put anything else in it, use quotation marks (either single or double, the same mark at each end) to tell the computer where the beginning and end of the text is, like this:

box myName is "Tom"
box school is 'Timbuktu High School #3'
box spacey is "    (some spaces)   "

When you are doing math, you can use the normal math operators '+' and '-' for add and subtract. There is no divide symbol on the standard computer keyboard, so we use the slant character ('/' on the same key as '?' but unshifted). Many of us learned to use an 'x' for multiply, but the letter 'x' could be confused with a variable named "x" so instead we use the star ('*' shift-8) to mean multiply. For text, the only defined operator is concatenate, which in the English computer is the hash symbol ('#' shift-3). Here are a couple examples:

let words be myName # " teaches at " # school
let sentence be words # " Begin + AddMe # " days."


When you have two or more values together like this with operations between them, it's called an expression. You can also combine multiple operators in a single expression. In school they teach you to do the multiplication and division first, then any addition and subtraction -- unless you use parentheses, and then you do what's inside the parentheses first, but otherwise the same rules. The computer works the same way. For example, the first two lines here compute the same value (11) but the third line computes the value 16.

let clean be 5+3*2
let complex = 5+(3*2)
let difft = (5+3)*2
Note that the equal symbol '=' in English is another way to spell "is" or "be", but it should not be confused with the algebra notion of an equation. Variable assignment happens only in computers, and it amounts to erasing whatever was written on that piece of paper, and writing a new value there. The previous value is gone.

In my examples, sometimes I use numbers, and sometimes (variable) names. The computer doesn't care, both work. We use numbers when we mean "exactly this value, not any other," and we use variables when we want to change the value next time around, or for different inputs. For example,

let one = 1
let two = 5
let some = one+2
let Sum = 1+two
let two = two-Sum
print "some=" some ", Sum=" Sum ", two is now " two


You see the name of the variable (in this case "two") has nothing to do with what value it has. Well, you should pick variable names that mean something to you (because otherwise you will forget what is going on), but the computer doesn't care.

The concatenate operator '#' gets used a lot. The English computer you are running this on asssumes the concatenation operator if you leave it out. Try it. See that PRINT line? We didn't type any concatenation operators, but they were assumed. This is what it really did for you:

print "some=" # some # ", Sum=" # Sum # ", two is now " # two


Most computer programming languages will not make these assumptions, you must explicitly use the operators.

Pretty soon we will get to writing a real program, a four-function calculator, but it uses variables and operators, and you need to understand how these things work. Be sure to sign in with your Zoom name and do these experiments, then come back and refresh this page...

Arrays in English

We have a word game coming up that requires the computer to pick individual letters out of a word, or else to poke (usually something else) back in. Most computer programming languages let you do this on the text of words (and English does too), but it's messy and hard to understand. The usual way to do this kind of thing in programming languages is the variable type called a "list" or more often "array", and it is a bunch of little pieces of data in some kind of numerical order, and you use iteration to get at the individual pieces in order.

You can learn how to do this now (keep reading), or you can delay until you get there (skip down to the bottom to start working on the calculator, then come back here to pick up where you left off).

Sometimes the order doesn't matter (like this shopping list) but computers do numbers very well, so that's what it is. In English we can refer to list items as "items" (or sometimes "lines") and usually we can cross off an item like when we already got it in our shopping cart or we changed our mind, but it doesn't lose its place.

We tried to make the English programming language work the same as the language "you already know," something like this:

List shopping {spoken English you'd say 'shopping is a List'}
Let item 1 of shopping = "Bread"
Let item 2 of shopping = "Meat"
...
Print shopping
Let shopping line 2 = "--Tofu"
And so on. You can also initialize your array in one line:
Array shopping = "Bread","Meat","Veggies","Ice cream"


The powerful thing about lists is that you can use iteration to access the numbered lines in order (or reverse order) like if you wanted to sort the items. This is called a "Bubble Sort" and it's pretty easy for small lists, but there are much faster sorts for big lists. Assume you have a list called SortMe with Nitems lines in it:

  Let SortMe = shopping
  Let Nitems = 4
  Do BubbleSort
  Print SortMe
...
"BubbleSort"
  Let fini = 1
  Repeat Nitems-1
    Let here = 1
    Let none = true
    Repeat Nitems-fini
      Let tmp = item here of SortMe
      Let nxt = item here+1 of SortMe
      If tmp > nxt then Do Xchange
      Add 1 to here
      Next
    If none then Exit
    Add 1 to fini
    Next
  Done
"Xchange"
  Let item here of SortMe = nxt
  Let item here+1 of SortMe = tmp
  Let none = false
  Done
Each time through the inner loop, the largest item "bubbles" up to the top of the list. After it's there, it is no longer necessary to compare that item, so the iteration is shortened by one, and the next largest item bubbles to the almost-top. Simultaneously, the smallest item bubbles down one unit. So the worst case, where the smallest item starts out at the end of the list, requires Nitems-1 times through the outer loop to get it all the way to the bottom.

You should experiment with making lists and moving things around
 

Substring Command

We have a word game coming up that requires the computer to pick individual letters out of a word, or else to poke (usually something else) back in. You can learn how to do this now (keep reading), or you can delay until you get there (skip down to the bottom to start working on the calculator, then come back here to pick up where you left off).

In English the word "word" refers to one or more letters together (with no spaces or punctuation) that has a particular meaning, like I just now explained for the word "word". Computers mostly don't know about meanings, but it's often useful to put letters and punctuations together into a piece of text that gets handled in a single variable. We do this a lot, so we need a single word to describe such a piece of text. It can (and often does) include spaces and punctuations, so the word "word" is misleading. Instead we call it a "string" to be thought of like beads on a real string or thread, like the picture here. So let's assume you have a variable necklace (like the picture) with a string of characters in it:

let necklace = "Hello World"


If we wanted to pick out some of those beads -- say for example the beeds in front, the letters "LLO WO" -- and make a copy on their own string, that would be called a "substring". This is so useful that every language that lets you work with strings at all has some way to extract substrings. In the English computer we do it with a command:

substring part = necklace,2,6


This isn't very much like the English you speak at home, so it needs some explaining. The command "substring" tells the computer what you want it to do.and the next word is a variable to put the result in. The equal symbol tells the computer that it must come from the variable (in this case) necklace. The next two numbers tell the computer how many characters to skip over (two, letters "HE"), and then how many letters to take (six).

The formal reference documentation is here in the Command Details section of the Kitchen Computer Reference Manual., which you can also get to from its link in the Quick Reference section at the bottom of the IDE page.

In the spirit of what I call the "Video Game Method" -- Hmm, I seem to be confronted by this blue orc, I wonder if the Photon Grenade works... Nope, well try the Laser Defragger... Not that either. After nothing I can think of to try works, call in the Mentor for help (or in the more general case, Google the question) and learn it was the Pixie Dust you neglected to pick up on Level 3 -- I offer this little test program for figuring out what the substring command (or any other command) does:

let necklace = "Hello, World!"
substring part = necklace,2,7
print "Got '" # part # "'"


Type it into the English IDE, then run it several times and fiddle with the numbers until you see what they do. Or you can use the IDE Step button to step through one line at a time and watch your variables.
 

Six Things You Already Knew (Summary)

There you have it. Every program anybody ever wrote is composed of commands, each representing one of these six things. You start with the name of what you want to do, and that becomes a subroutine name, the program that does it. You break that down into two or three parts, each with a descriptive name, and each part that is not one of these six things, you make it a subroutine name and repeat.

OK, let's review what we know about the Six Things:

A. A program is a sequence of steps to be executed in order -- in English these are the separate lines of your program, and in every progrmming language, each command (English line) does one thing -- except

B. If we tell it to repeat (an iteration), it jumps back and does some part of the sequence over and over -- in English we use "Repeat" and "Next" to set off an iteration -- or else

C. In a conditional we can tell the computer to omit some step based on some outside or computed condition -- in English that is the single line or partial line following the "If" command. In the usual form you get a choice, left or right, red or green, yellow or blue, yes or no, sometimes a choice from several like our choice of jams, but never both or all at the same time.

If you have one or more contiguous "If" commands (with what they do when the condition is True), you can follow them with an "else" or "otherwise" (or "any other") command, which gets executed only when none of the previous "If" commands were True. This doesn't work the way you'd want it to if your "If" commands are testing two or more different variables.

And what kinds of steps do we do in (or out of) order? We can do

D. Input (so far reading the date, later we will accept information from a human user -- "Input" -- like the previous bonus) and output (printing a message on the screen -- usually "Print" or "Say" or "Display" in English -- or changing some pixels in an image by reference to on-screen objects like jam or knife in English), and

E. Evaluating the value of a variable -- using the "Let" command -- which can then be used to control conditionals and iterations, and/or output to the human watching. Getting variables right is extremely important, because (other than PBJ) variables and expressions are used all the time when writing programs. If you are the least bit uncomfortable, you might should go back and review the math operations.

Those five things, every computer program, in its lowest detail, consists of those five things, and nothing else.

F. There is a sixth not-quite-primitive called subroutines, a sort of named box we can put around a bunch of steps so that you think of them as a unit -- which we invoke using the "Do" command -- the way in English we call the sandwich program "Make PBJ" but it says nothing about the steps you went through to make it (the lines that follow the title explain what to do). You don't need to think about what's inside the box after you know it works correctly.

Whenever you want to do more than one thing in a single command line, you use a subroutine. Then that one line does one thing, which is to call the subroutine (the subroutine call is one of our Six Things), and the subroutine does as much as you want, one command (always one of our Six Things) for each step.

It is important to remember that (in the English computer) that any quoted whole line is assumed to be the start of a subroutine, which ends with the command "Done" or a blank line; the same line without the quotes anywhere else in your program calls the subroutine (execution jumps to the subroutine and does all of it, then returns to the line after the call), but we recommend you use the command "Do" at the front of the call to make it obvious that this is a subroutine call (so the computer can let you know if you misspelled its name).

Our next program is no longer a PBJ sandwich, you will write a real program, a four-function calculator just like the one in your iPhone or you can buy for a couple bucks at the Dollar Store. Later we will rewrite the same program in Java. You will use the skills you learned in the PBJ, and you will use variables.

Turn the page for the Calculator.

[2022 September 29]