﻿ USING VARIABLES - LEARN TO PROGRAM WITH SMALL BASIC: An Introduction to Programming with Games, Art, Science, and Math (2016) ﻿

## LEARN TO PROGRAM WITH SMALL BASIC: An Introduction to Programming with Games, Art, Science, and Math (2016)

### 4. USING VARIABLES

Have you ever wanted to be a doctor, astronaut, firefighter, animator, mayor, botanist, or ninja? What if you could be all of them but just one at a time? A variable can be anything in your programs, like a string or a number, but it can only be one thing at a time. For example, a number-guessing game might ask the player to enter their name (a string) and then greet the player using that name. Next, the program might ask them to enter their first guess for the game (a number) and then check to see if they guessed correctly.

For the game to work, it must remember, or store, the data entered by the player. It also might need to track how many rounds it took the player to guess the secret number. You can do all this using variables!

In this chapter, you’ll learn how to define variables and use them to store text or numbers. You’ll then use variables in programs that solve practical problems.

What’s a Variable?

A variable is used to store values, like numbers or text. You can use it similarly to how you might use a treasure chest to store valuables if you were a pirate. Think of a variable as a box. You can put different things inside your box to use later on. You can change the value of your variable, just like you can put something new inside your box, like your gum collection. Variables are called variables because their contents can vary.

To create a variable in Small Basic, use an assignment statement like this:

treasureChest = "My booty!"

This statement creates the variable treasureChest and assigns it the string "My booty!" The equal sign is an assignment operator. Assigning a value to a variable for the first time is called initializing the variable.

Now let’s explore how to use variables in your programs. Anchors aweigh!

The Basics of Using Variables

Karen has 12 stuffed bears. Her sister, Linda, has half as many. How many bears does Linda have? You could do the math in your head or with a calculator, but let’s follow Listing 4-1 to do this problem the Small Basic way!

' Variables.sb
2 karenBears = 12             ' Karen has 12 bears
3 lindaBears = karenBears / 2 ' Linda has half as many bears as Karen
4
5 TextWindow.Write("Karen's " + karenBears + " bears aren't as ")
6 TextWindow.WriteLine("fancy as Linda's " + lindabears + " bears!")

Listing 4-1: Demonstrating variables

The statement karenBears = 12 at line 2 creates a variable named karenBears and assigns the value 12 to it. Line 3 divides karenBears by 2 and then stores the result in a new variable named lindaBears. When line 3 runs, lindaBears holds the value 12 ÷ 2, which is 6.

Line 5 outputs the string "Karen's ", and then the plus sign concatenates the value of karenBears, which is 12, after the string. Then it concatenates " bears aren't as " after the 12. (For a refresher on concatenation, refer to “Joining Strings” on page 18.) Similarly, line 6 outputs the string"fancy as Linda's " and then the value stored in the variable lindaBears. Finally, it adds " bears!".

Now, let’s run the program to see the result. You should see this:

Karen's 12 bears aren't as fancy as Linda's 6 bears!

Try changing the value in karenBears and running the program again to see what happens. Neat, huh? Changing the value of karenBears will also change the value of lindaBears. Variables can make your programming life so much easier!

Let’s check out some other important concepts you need to know for when you want to use your own variables.

Assigning Expressions to Variables

Arithmetic expressions are combinations of variables, operators, and numbers. They can be constant numbers (such as 3, 6.8, or –10), arithmetic operations (such as 3 + 6 or 10 / 3), or algebraic expressions (karenBears / 2). Evaluating an arithmetic expression in Small Basic is just like evaluating an expression in math. For example, the expression 4 * 3 + 6 / 2 is evaluated as (4 × 3 + 6 ÷ 2) = 12 + 3 = 15. You can also use parentheses in expressions to decide the order of operations.

You can set variables to the result of an arithmetic expression using an assignment statement. Your program grabs the value to the right of the equal sign and assigns that value to the variable on the left of the equal sign. You already did this in Listing 4-1; let’s build on that knowledge and write some more variables set to arithmetic expressions!

Here’s an example:

barbies = 5                     ' You have 5 Barbies
ponies = barbies + 7            ' You have 7 more My Little Ponies than Barbies
donate = (barbies * ponies)/ 10 ' Total toys you need to donate

When you run this program, the variables barbies, ponies, and donate are 5, 12, and 6, respectively. Time to donate 6 toys!

You need to set the variable on the left of an assignment operator, as you’ve seen in every assignment example so far. So this statement is incorrect:

5 = barbies  ' This is backwards, like the Twilight Zone

Try running it yourself to see if you get an error!

Passing Variables to Methods

A method’s arguments can be constants, variables, or even expressions. For example, the argument to WriteLine() in the following statement is an arithmetic expression:

TextWindow.WriteLine((3 * x + y) / (x - y))

If x = 7 and y = 5, this statement displays 13 on the screen. See if you can figure out how to write and run this code. Remember to set x and y first!

Changing the Value of a Variable

When you create a new variable in your program, you assign it an initial value using the assignment operator. You can also use the assignment operator to change the value of an existing variable, which wipes out the old value, like this:

ferrets = 5
ferrets = 15
TextWindow.WriteLine("There are " + ferrets + " ferrets in my bed!")

The first line in this example creates a new variable named ferrets and assigns 5 to it, but the second line changes its value to 15. So the WriteLine statement will output There are 15 ferrets in my bed!

Behind the scenes, the variable ferrets points to a storage area in the computer’s memory. When you write ferrets = 15, you tell Small Basic to go into the space in the memory reserved for ferrets and replace the 5 with a 15. When you display the value of ferrets, you grab whatever’s stored in the space at that moment.

You can also add to a variable to change its value. Imagine you’re programming a game in which the player has to shoot attacking airplanes. When the player shoots an airplane, you want to increase their score (stored in a variable named score) by five points. How would you update thescore variable? Here’s one way:

score = 10        ' Assumes the player already has 10 points
temp = score + 5  ' temp = 10 + 5 (= 15)
score = temp      ' Now the player has 15 points

The second line uses a temporary variable named temp to store the result of adding five to the current value of score. The value of temp is then assigned to score.

But you can do this faster in one statement:

score = score + 5

Do you see how the same variable, score, is on both sides of the assignment? This statement adds 5 to the current value of the variable score and then stores the result back into the same variable. The old value of 10 is replaced by the new value, 15. See Figure 4-1. Figure 4-1: Illustrating the statement score = score + 5

These two ways of updating the score variable are basically the same, but the second method’s more common, and you’ll see it all the time in other people’s programs.

Add tabs and spaces to make your expressions more readable. For example, look at these two expressions:

x=y+10*(x-3)-z
x = y + 10 * (x - 3) - z

They’re the same to Small Basic, but the spaces in the second line make it easier for humans (and other nonrobots) to read.

TRY IT OUT 4-1

The following program finds the average of the weekly hours you spend on homework for two classes. First, identify all the variables in this program. What does this program display when you run it? Try it out!

mathHours = 8
scienceHours = 6
avgHours = (mathHours + scienceHours) / 2
TextWindow.Write("I spend " + mathHours)
TextWindow.Write(" hours a week on math homework and " + scienceHours)
TextWindow.WriteLine(" hours a week on science homework.")
TextWindow.Write("The average of " + mathHours + " and ")
TextWindow.WriteLine(scienceHours + " is " + avgHours + ".")

Now swap in the actual weekly hours you spend on two classes. How long do you spend on homework? Show the results to your parents—it might be a good primer before you discuss your report card!

Rules for Naming Variables

The names you give to variables are called identifiers. Variable names can include letters (lowercase and uppercase), digits (0 to 9), and underscore characters (_). You can name variables anything, as long as you follow a few rules:

2.    Don’t use any of Small Basic’s keywords, like If, Else, Then, And, or While. These keywords have special meanings, and they can’t be used for anything else. You’ll learn more about them later in this book.

3.    Variable names in Small Basic are case insensitive; side, SIDE, and siDE are the same variable.

Based on these rules, MyAddress, totalScore, player1, sum, room_temperature, and _x123 are all valid variable names.

In addition to the rules we mentioned, programmers also use other guidelines when naming variables. These conventions are good programming practices, and you should follow them, too. Let’s look at these additional conventions.

Say What You Mean

Although you can name a variable anything, we recommend you choose a name that explains what the variable is for. For example, using a variable named address to store a person’s address makes more sense than using a variable named xy123 or TacoTruck.

Find the Right Length

Avoid single-letter names like m, j, x, and w, unless their meanings are very clear, or you’ll just make your program harder to read and understand. But don’t use names that are so long that they put your friends to sleep, either!

Choose short, meaningful names instead. For example, use name or presidentName instead of the_name_of_the_president.

It’s currently popular to name variables by starting with a lowercase letter and then capitalizing the first letter of each additional word, like sideLength, firstName, roomTemp, variablesAreAwesome, and scoobyDoo. This naming style is called camel case because it has a hump in the middle. But don’t worry—camel-cased variables won’t spit!

This book uses camel case, but if you prefer a different style, that’s okay. Just use one naming convention and stick to it! Although Small Basic is case insensitive when it comes to variable names, you should be consistent about casing when you name your variables. If you name a variable firstName, use the same capitalization throughout your program. This makes it easier for you to find variables and for others to understand your code. The IntelliSense autocomplete feature can help you. Let’s see how.

Let IntelliSense Work for You

When you create a variable in your program, the name of that variable is added to the IntelliSense drop-down menu. When you want to reuse a variable (or check its case), just type the first few letters and look for it in IntelliSense, shown in Figure 4-2. Small Basic finishes your variable names, just like a best friend who finishes your ... sandwiches! Note how the name of the variable created in the first statement (interestRate) appears in the menu. When I started to type in on the second line, the IDE highlighted the name of the variable. Pressing the ENTER key autocompletes what I started to type. Thanks, IntelliSense!

Avoid Naming Variables After Methods and Objects

Method names aren’t reserved keywords, so you could use them as variable names. For example, Small Basic won’t complain if you write this:

writeline = 5
TextWindow.WriteLine(writeline)

Although this is valid, we strongly recommend you don’t name your variables after existing methods. The world is confusing enough already.

TRY IT OUT 4-2

1.    Which of these variable names are invalid? If the name is invalid, explain why.

_myBooK
1MoreRound
\$FinalScore
Level2

2.    For each of the following values, what would you name a variable that represents it, and why?

• The score of a player in a game

• The hypotenuse of a right triangle

• The number of floors in a building

• The number of miles a car can drive per gallon of fuel

• The number of licks it takes to get to the center of a Tootsie Pop

Simplifying Expressions

Variables can make calculating arithmetic expressions easier. Let’s say you want to write a program that evaluates this expression: You can write a bunch of different programs that would all give you the right answer. For example, you could write a statement that evaluates the whole expression at once:

TextWindow.WriteLine((1 / 5 + 5 / 7) / (7 / 8 - 2 / 3))

Or you might evaluate the numerator and the denominator separately and then display the result of their division:

num = (1 / 5) + (5 / 7)         ' Finds the numerator
den = (7 / 8) - (2 / 3)         ' Finds the denominator
TextWindow.WriteLine(num / den) ' Does the division

You could also evaluate each fraction separately and then display the result of the combined expression:

a = 1 / 5
b = 5 / 7
c = 7 / 8
d = 2 / 3
answer = (a + b) / (c - d)

Although these three programs give you the same answer, each program uses a different style. The first program is the “chubby bunny” of programming: it crams everything into one statement. If the original expression was more complex, the statement would be really hard to follow. The third program does the opposite: it represents every fraction in the expression with a variable, and that can also be hard to read.

If you’re Goldilocks, the second solution is your “just right.” It breaks down the expression into just enough parts to make the program easier to understand. The variables num and den clearly represent the numerator and the denominator.

As these examples show, there’s often more than one way to solve a problem. If you ever get stuck on a problem, try breaking it into more manageable pieces!

TRY IT OUT 4-3

Write a program that evaluates the following expression. Try taking a couple different approaches. Try doing it while dancing! Don’t be shy! Using Variables to Solve Problems

People often solve problems without really thinking through every step of the process. But computers can’t do this: they need you to think through each step for them (at least until The Terminator or The Matrix come true). That’s why it takes some planning to use a computer to solve a problem. When developing a solution to a programming problem, you should do this:

1.    Understand what the problem is.

2.    Design a solution.

3.    Write the program.

4.    Test the program to make sure it works as you expect it to.

Let’s say you want to create a program that computes the area of a circle with a given radius. To solve the problem, you need to answer these basic questions:

1.    What do you need the program to output?

2.    What input do you need, and where will the program get this input from?

3.    What processing will the program have to do to turn the input into the output?

For this problem, here’s how you’d answer those questions:

1.    Your program needs to output the area of a circle. It’ll show this output to the user in the text window.

2.    This program needs a single input from your user: the radius of the circle.

3.    Your program will need to compute the area using this formula, which might be familiar from math class:

NOTE

The Greek letter π, pronounced pi, is a special number that can be rounded to 3.1416. We gave you free pi!

Now that you’ve defined your problem, let’s design a step-by-step solution, which is called an algorithm. First, we’ll break down each part of the problem (the input, processing, and output) into detailed steps.

Get in the habit of writing an outline of the program that puts each step in order. This outline is called pseudocode because it’s not a real program, but it explains what the code should do. Looking at your pseudocode should give you a clear idea of the real code you’ll need to write for each step. For complex problems, pseudocode helps you express your thought process in simple terms that you can then translate into real code. Figure 4-3 shows our algorithm and pseudocode for the circle area problem. Figure 4-3: Algorithm and pseudocode for calculating the area of a circle

The final step is to translate your pseudocode into a Small Basic program. Because we haven’t shown you how to get values from the user yet, you’ll use a fixed number for the radius. Enter the program in Listing 4-2.

' CircleArea.sb
4 TextWindow.WriteLine("Area = " + area)

Listing 4-2: Computing the area of a circle

In line 2, you create a variable named radius and assign it a value of 5. In line 3, you compute the area of the circle using the formula from page 51 and assign the result to a new variable named area. In line 4, you display the value of the variable area after the text "Area = " to make it clear what the displayed number means.

When you run the code, you’ll see this:

Area = 78.5400

TRY IT OUT 4-4

Write a program that calculates and displays the circumference of a circle with a radius of 5 units. We’ll give you a hint: the equation for the circumference of a circle is 2 × π × radius.

Two Kinds of Data

Programs use all different types of data: applications that do calculations use numbers, but others might use text.

Small Basic uses very simple data types. It has built-in support for just two data types: numbers and strings. Numbers can be integers, like –2 and 2365, or decimal numbers, like 0.25 and –123.78. As you know, strings are characters strung together between double quotation marks, like"The Declaration of Independence" or "She sells seashells by the seashore."

You don’t need to tell Small Basic what type of data you’re going to store in a variable. This is a beginner-friendly way of programming.

Global Variables

Variables in Small Basic are global in scope. This means you can define a variable and access a variable from anywhere in your program. This feature is helpful because it lets you define variables just when you need them (instead of having to put all your variables at the top of your program). But you have to be careful! Because Small Basic reads your programs in order, it’s possible to create logical errors. Try the program in Listing 4-3.

' LogicError.sb
2 y = x / 10
3 x = 20
4 TextWindow.WriteLine("y = " + y)

Listing 4-3: Logic error with global variables

If you’re reading this code closely, you’ve already noticed that, in line 2, we’re using the variable x before we’ve assigned it any particular value. When we run this code, we get the following output:

y = 0

Does that answer surprise you? Here’s what’s happening. When the Small Basic compiler reads this code, it first makes a list of all the variables you defined in the program. The initial values for these variables are left empty, like empty boxes. As long as the expressions in the program use variable names from that list, the compiler’s happy and the program will run.

When the program runs the expression x / 10 in line 2, it interprets x as a number because division only makes sense for numbers. That’s why it fills the empty box for x with 0. It then assigns the result of the division (which is 0) to y. The variable x is changed to 20 in line 3, but it’s too late! You get the wrong output.

NOTE

Most other programming languages would report a syntax error because the expression x / 10 in line 2 uses a variable x that hasn’t been defined yet in the program. Small Basic lets you define variables anywhere in your program; just don’t expect to get away with it in other languages.

Be careful when you order your statements because Small Basic runs top to bottom. Make sure you define your variables before you use them for the first time.

TRY IT OUT 4-5

What’s the output of this program? Explain what you see.

TextWindow.WriteLine("Before: x = " + x + " and y = " + y)
x = 10
y = 10
TextWindow.WriteLine("After: x = " + x + " and y = " + y)

Programming Challenges

If you get stuck, check out http://nostarch.com/smallbasic/ for the solutions and for more resources and review questions for teachers and students.

1.    Do you like knock-knock jokes? Try the following program to see how to tell them in Small Basic! Which program lines do you need to change to tell a different joke? Make the change and run the program again to see what happens:

' KnockKnock.sb
' Small Basic can tell knock-knock jokes!

name = "Orange"

TextWindow.WriteLine("Knock Knock")
TextWindow.WriteLine("Who's there?")
TextWindow.WriteLine(name)
TextWindow.WriteLine(name + " who?")
TextWindow.WriteLine(name + " " + reply)
TextWindow.WriteLine("")

2.    Translate this pseudocode into a Small Basic program:

a. Set quantity to 10.

b. Set item price to 15 dollars.

c. Compute total price by multiplying quantity by item price.

d. Display total price.

﻿

﻿