In this lesson students will add variables to a program to keep track of a score, or a count of some number of key presses. The major topic is variable scope and understanding the differences, benefits, and drawbacks, of using global versus local variables. This lesson focuses more on using global variables, since in event-driven apps that's what you need to keep track of data across multiple events.
The very basics of a simple if-statement are also presented in this lesson. Finally, students are asked to apply what they've learned about variables, scope, and if-statements to make their own game modeled after one of the examples they saw during the lesson.
Students will be able to:
This lesson is mostly a continuation and furthering of our understanding of variables and how they work. There are many pitfalls and misconceptions about variables and how to use them in programs for the early learner. Variables are often difficult to learn because they are abstract, and one must have a good mental model for what"s happening in the computer and with program instructions, in order to reason about the code and develop one"s own solutions to problems.
The topic and concept of variable scope is a big one in any programming language. However, since many languages do it differently, the concept of variable scope isn"t listed explicitly as a learning objective in the CSP framework. As a concept, though, variable scoping is a form of abstraction - a programming language lets you create variables with as narrow or broad a scope as you need to program a certain task. As a general practice, you usually want to create variables with the most narrow scope you can for the task at hand, since the other extreme - everything is global - can become unwieldy or hard to manage, and it doesn"t promote code reuse.
Recall: In the previous lesson, students learned about the basic mechanics of working with variables in Quorum Programming Language. They developed a mental model for thinking about how values are stored and retreived from memory and that to avoid confusion they should read the "=" sign as "gets" when assigning values to a variable.
Moving Forward: The whole purpose of learning about variables though is so that programs can make use of them while they are running.
There are a few things that students need to understand about where to create variables in their code and how to refer to them. In this lesson students will learn how to do this and how to debug a few problems related to common issues that newcomers may have with variables.
Students will also use if-statements in this lesson to make certain changes once the score reaches a certain value.
The example program below has a portion of the Count Up/Down App written. Right now, the program should output an increasing count when the "UP" key is pressed on the keyboard and output Down when the "DOWN" key is pressed on the keyboard.
This small functionality demonstrates and important concept - how to create a variable in the app &quorcount" and update it when an event occurs. It may seem fairly straightforward but there are common misconceptions that we want to alert you to.
You are going to do a small investigation of two apps that do almost the same thing, but one works as expected and one with a bug that demonstrates an important concept about using variables in programs and apps. Here is what you'll do:
Respond to the following questions about your investigation into the bug with the counting game. Feel free to go back and run or examine the code for the game again.
Creating Variables in the Right Place: The problem you encountered was caused by declaring the "count" variable inside of the event handling action. In the second version, when you press the "UP" key:
This code works as expected the first time the "UP" key is pressed, but then when the "UP" key is pressed again it goes through the entire sequence again recreating the "count" variable with a value of 0, before incrementing the value and outputting the current value which will continue to be 1 over and over again every time the "UP" key is pressed.
Solution: Instead of declaring (creating) a new variable inside of the event handler, declare (create) the "count" variable and set the value to 0 in the Main part of the program and increment the value of the variable when the "UP" key is pressed.
In Quorum Programming Language you have two choices:
The term for this is "variable scope". The scope of a variable defines which parts of your code can access and modify the variable. Quorum Programming Language has two scopes: global and local. Here's the difference...
Variables created within an action become local to the action. Local variables have local scope: they can only be accessed within the action. In the example below we say that age is "local to" SomeAction() which means that only code within SomeAction() can access and modify the value of age. Code that is outside of this action does not know that the variable exists and therefor cannot use the variable. In fact, local variables are created when an action starts, and destroyed when the action is completed. Local variables only exist for the life of one action call.
// code here CANNOT use the variable age action SomeAction() integer age = 17 end // code here CANNOT use the variable age
A variable declared outside of an action, becomes global. A global variable has global scope which means the variable is accessible and modifiable throughout your program by any code, and also in any action. In the example below we say that lives is a global variable.
integer lives = 3 // code here CAN use and modify the lives variable action SomeAction() // code here CAN ALSO use and modify the lives variable end
Local variables are useful temporary placeholders for data that you need to perform a computation of some kind. Often a program will have several actions that perfom different but related tasks, and you'd like to reuse variable names. Since local variables are only recognized inside of their actions, variables with the same name can be reused in different actions.
The best example of this is action parameters. Action parameters are a form of a local variable - they get created and initialized when an action is called, they get used while the action runs, and then they get destroyed when the action completes.
Imagine if all we had were global variables. Then you could not write this code:
action Add(integer a, integer b) integer result = a + b end action Subtract(integer a, integer b) integer result = a - b end
If all variables had to be global we'd have to invent different variable names for every action parameter in the entire program. But because the a and b variables are local to the action, we can re-use these handy parameter names.
Global variables are useful for keeping track of data over the lifetime of the program that's running. If you want to keep track of some data between events, or between action calls, you want a global variable.
Where to Create Global Variables: By convention global variables are created and initialized in the very first lines of code in a program. This convention is helpful because it keeps all of the global variables in a group at the top where you can easily reference them.
You now know enough about using global variables to try it yourself. Let's start with an easy task. Right now pressing the "UP" key on the keyboard works as expected; pressing the "DOWN" key does not. So make the count go down by 1 every time the "DOWN" key is pressed on the keyboard.
The program below has a few different bugs. Do this:
Now that you know how to use variables in your program to keep track of useful information, the next thing you probably want to do is make decisions based on the variable's values. For example: in the Count Up/Down program what we want to say is "if the count reaches 10 then the player wins." We are going to learn all about "if-statements" in a later lesson. For now, we need to know just enough to make our program end.
We want to add another "if-statement" into the event handler to check the value of "count" immediately after we update its value. Here is an example of the full event handler:
action PressedKey(KeyboardEvent event) if event:keyCode = event:UP count = count + 1 if count = 10 say "You have reached 10, You Won!" else say count end elseif event:keyCode = event:DOWN count = count - 1 say count end end
Most programming languages have a way to check if some condition is true, and if it is do something. It's called an "if-statement". An if-statement does not constantly monitor your program checking the condition to determine if it's true or false. An if-statement is an instruction just like any other that gets executed line by line in order from top to bottom. This means that you need to insert an if-statement into your code at the exact place where you need the condition checked. Once the condition is checked, program execution picks up at the "end" of the if-statement and proceeds from there. This is why we need to check the value of "count" EVERY time the "UP" key is pressed. So that means the if-statement must be written into the event handler for the "UP" key, and checked after we update the value of "count".
In most programs/apps you want to make decisions based on the state of the data you're keeing track of in the app. We have shown you how to add the if-statement structure to the "UP" key press. Now it is your turn to add some code for the "DOWN" key press that will say the player "lost" if their number reaches -5.
You will be creating your own game similar to the Count Up/Down app you have been working with in this lesson. The general object of the game is to use all 4 of the arrow keys to count up or down to reach the "Goal" number. For example you could set the:
If the player's "counter" equals the "goal" number within a certain amount of key presses (or lives) then they win the game, otherwise they lose. Your main tasks are to:
We have provided you with a template to get started. Refer to the pseudocode under the "UP" key press in the event handler to determine what you will need to include in the case of each key press and where to place those statements within each section. Remember that every "if-statement" structure needs to have an "end" as shown in the previous examples in this lesson.
Have students try out and evaluate their classmates' apps. It is up to you to determine who should evaluate which programs, how to pair students, and the degree of anonymity you wish to maintain. Peer review should be a useful activity for students in preparation for the Create Performance Task in which they need to give and receive feedback with a partner to improve their programs.
Transition: Now that we understand a bit about variables and how to use them in our programs, a whole new world will open to us. First, we will learn that variables can hold other kinds of data besides numbers. We'll also learn other ways to get data from the user using other UI elements like text input.