This lesson gets into the basic mechanics of working with variables in programs. The lesson shows students how to create and assign values to variables and navigates through a series of common misconceptions about variables and how they work. Along the way, the lesson tries to build up the student's mental model of how computers and programs work, which is essential for being able to reason about programs.
Students will be able to:
Developing a good mental model for how variables work in computer programs is absolutely essential to long-term success as a programmer. However, because most students have had years worth of math classes before taking this course, there are two major misconceptions that early students often have about variables. We suggest that you try to avoid relating this material to mathematics at all. Some of the words and symbols are the same, but:
Thus, lines of code that assign values to variables and expressions that use variables are really instructions to retrieve and store values in memory. And those values change while the program executes. Consider the following lines of code:
a = a + b b = a + b
Being able to reason about what's happening in consecutive lines of code like these correlates highly with a person's success in programming because you must have a good mental model for program execution and what the computer is doing.
You are now pretty well acquainted with the basic mechanics of making event-driven apps. There is a pattern to writing these programs that you should be used to:
However there's a whole bunch of things that we can't do in our apps yet. The next step is to learn how to control the computer's memory to remember things while the program is running.
Most apps keep track of some information that changes and updates as you use the app. For example, a simple game can keep track of your score and the number of lives you have left as you play.
Note that keeping track of data while a program is running is different from remembering things in the long term across multiple uses of the app, things like storing the all-time high score or remembering your user profile. Most programs need to use memory for even basic processing tasks.
But you will want to write programs that keep track of data. These apps/programs use and control the computer's memory to do this, and learning how to use memory in programs is a powerful skill to have. Today we'll start!
The programming tasks in this lesson acquaint students with the basics of working with variables and building up a mental model for how programs use and manage memory. To keep things simple, the output will mostly be simple text displayed to the screen.
This lesson gets into the basic mechanics of controlling the computer's memory, by working with variables in programs.
We're going to focus on some bare-bones examples so that students get the basic ideas behind creating and using variables. We will be displaying text in the console rather than enhancing an app for now.
Understanding the typical pitfalls of learning variables for the first time, combined with establishing a good mental model, will make working with memory and variables in the future much easier.
In the next two lessons students will learn how to work with variables and then incorporate them into a game to keep score.
In this lesson students will learn to:
Let's get started with the most basic example of using and controlling the computer's memory with variables.
//Creates a text type variable named "teamName" and assigns the value of "Tigers" to it text teamName = "Tigers" //Creates an integer type variable named "score" and assigns the value of "0" to it integer score = 0 //Displays a message that includes the "teamName" and the current "score" to the output screen output "The " + teamName + " current score is: " + score
Create/Declare an integer variable "lives," assign it a value, and then display it to the console using a descriptive message that indicates what value is being displayed. Use the example above to help you.
See if you can find the error in the following code block. If you are having trouble locating the error try running the program, fix the error and run it again.
When you get the program running correctly the output should be:
When you are displaying the "value" of a variable to the output screen you should NOT use quotes. Notice the difference between these two statements - the comments next to each line explains the differences:
output "score" //will display the literal characters s-c-o-r-e output score //will retreive the value of score and display it
integer score = 0as: "The variable score gets the value 0" or maybe just "score gets 0" to be brief. Another example:
integer newScore = score + 1should be read as "newScore gets score plus 1."
When you read the = sign as "gets," and say it out loud that way, you'll prevent confusing yourself, and other programmers will know what you are talking about.
As we're about to see there are other ways to store values in variables besides just hard-coding single numbers. But in all cases, even when it's more complicated, using the word "gets" when you see a variable assignment will help you create a mental model of what's happening.
A common thing to want to do is store the result of an arithmetic expression. The 4 basic arithmetic operations + - * / are available.
integer result = 7 + 3 //stores 10 in "result" integer value = 7 - 3 //stores 4 in "value" integer score = 7 * 3 //stores 21 in "score" number bonus = 7.0 / 2.0 //stores 3.5 in "bonus" integer average = (10 + 15 + 10 + 20 + 15) / 5 //stores 14 in "average"
The expression itself is NOT stored in the variable, rather with arithmetic instructions like these you are asking to compute the expression first, and then store the answer (a single number) in the variable.
output "The " + teamName + " current score is: " + scorestatement.
If both operands are numbers "+" means to add those two numbers together.
integer num1 = 5 + 7 //stores the sum of 5 + 7 (12) in the variable num1 output num1 + 10 //outputs the sum of variable num1's value (12) and 10 to the screen, in this case 22
If either of the operands is a string "+" treats both operands as if they were strings and combines them to create a single string. This is potentially confusing behavior especially if the text looks like numbers. For example this code block will display 16100 to the screen.
integer num = 100 output "16" + num
This is because Quorum Programming Language sees that you are trying to display a mix of text and variable values. "16" (in quotes) is a string of ASCII characters not a number. And so everything is converted to text and the characters in the result of "16" + "100" comes out to "16100".
Tip: It's common to want to sandwich a variable between some text when displaying it. You can "add" together multiple pieces of text and variables using the "+" operator. For example, you can do this:
integer numLikes = 7 output "So far " + numLikes + " people like this page." say "So far " + numLikes + " people like this page."
We have given you the starting code shown below. You should modify the code by combining text and variables to output/say this single line of text "You have 3 lives left with score: 0."
Arithmetic becomes much more interesting when we use other variables in our expressions. For example you can do this:
number quiz1 = 99.5 number quiz2 = 89.0 number quiz3 = 93.5 number avg = (quiz1 + quiz2 + quiz3) / 3
The end result of an expression with variables is the same as one without. The major difference is that values are retrieved from memory in order to do the calculation rather than simply hard-coded. To compute the expression the computer will:
In the starting code we have provided you with variables that might be the kinds of things you would keep track of in a game totalTime, points, and lives.
Right now the totalScore is set to 0. We want you to compute a totalScore so that the person is rewarded for having a lot of points and lives, but penalized for taking a lot of time.
Write an expression to calculate the player's total score and store that calculation in the totalScore variable. The calculation you should use is: the player's points times their lives divided by the totalTime.
For the values provided the program output should be:
Points: 15 Lives: 3 Total Time: 9 ------------------------------------ Your total score is: 5
Programs become much more interesting when the values in variables change while the program is running. We can also assign to a variable the value returned by an action. Remember our random number generator from Lesson 2 where we used the following line of code:
integer randomInt = random:RandomIntegerBetween(1, 10)
Because the RandomIntegerBetween() action evaluates to an integer, it means that we can treat it as though it were a number.
Using the template below, create a program that simulates the rolling of two dice and reports (displays) their individual values as well as the sum. The program should:
Every time you run the program the result will be a little different.
We have given you starting code that explains what to do for the first die. The rest of the code is up to you! When you are done the output in the app display should be similar to this:
Rolling Dice! You rolled a: 5 and a: 2 For a total of: 7
Programs become even more interesting when we can interact with the user. To store user input into a variable we would use the following line of code:
text name = input("What is your name?")
This will prompt the user with the message "What is your name?" and store the user's input into the text type variable "name." Since all user input is read in as a text type, we will have to manipulate the input to change the data type for our specific purpose. For instance if we want to store user input in an integer type variable we would have to place a "cast" on the input like this:
integer age = cast(integer, input("What is your age?"))
This will prompt the user with the message "What is your age?" and then cast (change) the user input to an integer type and finally store the value in the integer type variable "age."
Note: If you try and "cast" the text value "bob" to an integer type value, you will receive what is called a cast error since "bob" is NOT an integer, but a name.
Let's use the technique of casting user input to make a simple calculator. Write a program that will:
We have given you starting code that shows you how to get the first number, the rest of the code is up to you.
Debugging Tip: Every start parenthesis "(" needs and end parethesis ")".
So far we have only set a variable's value once. But it's called a variable for a reason - its value can change (or vary) throughout a program. This is useful and necessary for keeping track of things like a score in a game.
To re-assign a value to a variable all you have to do is maintain a mental model of what's happening:
Make a Prediction: Study the code in the online IDE below and make a prediction about what will happen when you run the code. What will the values of a and b be at the end of the program?
Add an output statement at the end of the code for both variables to see if you were correct. If not, go back and add output statements for the variables throughout the code so that you can see the change in the variable's value as it occurs.Notice: In the code below, after the integer type variable "a" has been created using
integer a = 3to change a variable's value, you only need to refer to the variable by its name. The type "integer" only needs to be used once - when the variable is being created (declared) for the first time. It is a common mistake to use the type everytime you want to use a variable, but just remember that when you include the type you are creating a new variable. The computer will give you an error if you try to create the same variable more than once.
All of our examples so far have shown how to set the value of a variable by using combinations of numbers and other variables. But what if you wanted to do something like add 10 to the current value of a variable?
Because updating the value in a variable is just moving memory around, the process has to go something like this:
The technical term for this is called variable re-assignment - when you change the value of a variable based on its current contents. To increase the value of "num1" by 10 you would need to do this:
num1 = num1 + 10
Make a Prediction: We start you out with some code again. Trace the code and predict what you think the output will be at each step. Run the program and see if you were right. Add an output statement at the very end to see the last value of someNum and see if your full prediction is correct.
The next two challenges present coding tasks related to "moving memory" around in your program
Goal: Set the value of the variables to make the output display the defined "Expected Output"
Example: Provided Code
integer x = 2 integer y = 3 //your code goes here output "The value of y is: " + y + "(y should be 5)"
Example: Possible Solution
integer x = 2 integer y = 3 //your code goes here y = y + x output "The value of y is: " + y + "(y should be 5)"
Now you try one. Use the starter code below to display the expected output:
Okay let's try one that is a little bit harder:
Hint: This one requires you to be a little clever. Think about setting the value of one variable that you could then use to easily set the value of the other variables. Then the trick is to figure out how to use the variables you've been given to make that useful value.
Hopefully you now understand the gist of working with variables. The example below is something that definitely wouldn't make sense in math class, but you should be able to reason about it as a piece of code. Because it's code, you can also insert statements to display the value of the variables as they change. You don't have to guess!
integer num = 0 num = num + 1 num = num + 1 num = num + 1
This lesson was subtly one of the most important for you as a programmer. Being able to predict the value of a variable by tracing the code means that you have a good mental model for how programs execute code and how machines work.
Some research has shown that being able to answer questions about simple variable re-assignment correlates highly with doing well in programming overall. So you're on your way!
Students can make their own program that prompts the user for some numeric values and then performs an action. The user input values could be used to print a calculation to the screen, or they could be used to control a program (such a the number of times to repeat an action).