LEARN TO PROGRAM WITH SMALL BASIC: An Introduction to Programming with Games, Art, Science, and Math (2016)
2. GETTING STARTED
Now we’ll walk through some code step-by-step, so you can learn about the important pieces. As you read, enter the examples, and we’ll explain how to run them and modify them. But don’t stop there: experiment to give your programs a personal touch. We’ve included exercises at the end of each section to help you become a programming master (like a Jedi, but without the dangerous lightsabers). Try out the exercises to hone your skills.
The Parts of a Program
Let’s explore the different parts of a program by looking at a simple example. Listing 2-1 shows a program similar to the Greetings.sb program you wrote in Chapter 1. Enter this program into the Small Basic Editor, and then click the Run button on the Toolbar (or press F5 on your keyboard) to run it.
1 ' Welcome.sb
2 TextWindow.WriteLine("Welcome to Small Basic.")
Listing 2-1: Writing a welcome message
These two lines are the source code of your Welcome.sb program. When you run this code, you’ll see an output window that looks like Figure 2-1. (Note that the window’s title shows where we saved the file, so yours could be different.)
Figure 2-1: The output window for Welcome.sb
Your console window will look slightly different from this one, since the window has a black background by default. For the rest of the book, we’ll show the output as text, except when it’s necessary to see the window.
Small Basic automatically adds the text Press any key to continue... to the window to give you a chance to view the output (there isn’t an any key on your keyboard, so don’t look for it). Otherwise, the screen would flash your output and disappear.
Comments and Statements
The line that starts with a single quote (') is called a comment. You can add comments to explain what your program does, and Small Basic just ignores them. The comment on line 1 is the name of the file that contains your source code.
You should get into the habit of commenting your code, because you’ll often head to the forums or to friends for help, and they’ll need to understand what your code is trying to do.
The Small Basic Editor shows all comments in green so you can easily tell them apart from lines of actual code, which are called statements. Comments make programs easier to read, and you can add them anywhere! But be careful not to use too many comments, or you might make your code even harder to read! It’s a good practice to write comments at the beginning of your code to describe your program or to explain any tricky parts.
If you add a blank line that separates the comments from the code, Small Basic also ignores it, so add as many empty lines as you need to make your program easier to read! Line 2 in Welcome.sb is your program’s first statement, and that’s where the program begins executing. (Don’t worry: nobody dies!)
Figure 2-2 shows the parts of our statement. Let’s break it down and see what each part does!
Figure 2-2: The statement in Welcome.sb
TextWindow is an object built into Small Basic that takes text input and sends text output to your screen. WriteLine() is a method of the TextWindow object. This method displays the data passed to it in the output window. When you use TextWindow.WriteLine(), you tell the TextWindow object to execute its WriteLine() method. This is known as dot notation because of the dot between the object and the method. Dot notation is used to access an object’s method and follows this format: ObjectName.MethodName(Arguments). In this example, "Welcome to Small Basic." is an argument to the WriteLine() method. It tells the method exactly what you want to write.
Characters and Strings
Letters, numbers, punctuation marks (dot, colon, semicolon, and so on), and other symbols are called characters. A sequence of these characters surrounded by double quotes is called a string. The quotation marks show where the string starts and ends.
In our Welcome.sb program, the text that reads "Welcome to Small Basic." is a string.
Arguments and Methods
You pass arguments to a method inside its parentheses. An argument can be a string, a number, or some other value. The WriteLine() method accepts only one argument, and in your Welcome.sb program you pass it the string "Welcome to Small Basic." as its argument.
Click the WriteLine() method in the Editor, and check Small Basic’s Help Area (Figure 2-3). It’ll show you what kind of data to pass to that method.
Figure 2-3: The Help Area information for the WriteLine() method
The Help Area is your friend! Read it to avoid needless mistakes and frustration.
TRY IT OUT 2-1
Point out the object, method, and arguments in these calls:
1. Shapes.AddRectangle(100, 50)
2. Math.Max(5, 10)
Exploring Other Features
In this section, you’ll explore other key features of Small Basic by making small changes to the Welcome.sb program. Each example highlights a different feature, so let’s jump right in! Small Basic is warm and inviting!
You originally entered TextWindow.WriteLine("Welcome to Small Basic."), but Small Basic wouldn’t care if you changed the case of any letter in TextWindow or WriteLine. For example, you could write: TextWindow.writeLINE("Welcome to Small Basic."). This gives you the same output as before because Small Basic is case insensitive, which means that it doesn’t matter if your code is written in uppercase or lowercase letters.
Identifiers like Writeline, writeline, and WRiTeLiNe are all interpreted the same way by the compiler, which reads each line of code and builds the application. But you should get into the habit of respecting the case of identifiers because other languages are case sensitive. Small Basic is like a friendly coach who won’t yell at you for improper capitalization. It’ll even fix your typing mistakes for you, thanks to IntelliSense’s autocorrect function.
But what happens if you change the string? Try entering the welcome message in all capital letters:
TextWindow.WriteLine("WELCOME TO SMALL BASIC.")
When you run this program, WELCOME TO SMALL BASIC. is displayed in all capital letters in the output window. Why? The reason is that Small Basic’s WriteLine() method displays anything between the quotes exactly as you wrote it!
Listing 2-1 displays only one line of text, but you could display as many lines as you want. Let’s follow Listing 2-2 to extend the program to display three lines!
1 ' ThreeLines.sb
2 TextWindow.WriteLine("Welcome to Small Basic.")
4 TextWindow.WriteLine("Anyone can code!")
Listing 2-2: Displaying more lines
When you run this program, you’ll see this output:
Welcome to Small Basic.
Anyone can code!
Your program’s output shows that each line is executed in the order it’s listed in the program, from top to bottom. Do you see that empty line in the output? That was made by the statement in line 3 where you gave WriteLine() a pair of double quotes with no characters inside them. Because "" contains no characters, it’s called an empty string. Empty strings are useful when you want to display empty lines to break up the program’s output and make it easier to read.
Displaying Numbers and Doing Math
You can also use WriteLine() to display numbers. Try out Listing 2-3.
1 ' TextAndNum.sb
2 TextWindow.WriteLine("5 + 7")
3 TextWindow.WriteLine(5 + 7)
Listing 2-3: Showing the difference between strings and numbers
Here’s the output of this program:
5 + 7
When you pass anything to WriteLine() in double quotes, the output window shows exactly what’s inside the quotes. So, when you pass "5 + 7" to WriteLine() in line 2, Small Basic treats the plus sign inside the string like any other character and doesn’t see it as an addition problem!
The WriteLine() command on line 3, however, is different. You passed 5 + 7 to WriteLine() without double quotes. In this case, Small Basic understands that these are numbers, not parts of a string. Behind the scenes it adds 5 to 7 to get 12 and passes the sum to WriteLine().
You can also add strings together to build sentences or add to phrases, as shown in Listing 2-4. Combining strings is called concatenation.
1 ' JoinString.sb
2 TextWindow.WriteLine("Hello," + " oblate spheroid!")
Listing 2-4: Explaining concatenation
In line 2 of Listing 2-4, the WriteLine() method takes two strings, "Hello," and " oblate spheroid!", with a plus sign (+) between them. In this case, because you’re not performing addition, the plus sign has a different meaning: it’s called a concatenation operator, which joins two strings together into a single string. Notice the extra space in " oblate spheroid!". It makes your message display with a space between the words.
The plus sign (+) glues "Hello," onto " oblate spheroid!" and creates the new string "Hello, oblate spheroid!".
You can also join strings and numbers together. Small Basic automatically converts any number to a string so that concatenation can do its thing! Take a look at Listing 2-5 and its output in Figure 2-4.
1 ' JoinNum.sb
2 TextWindow.WriteLine("Let's concatenate: 5 + 7 = " + 12)
Listing 2-5: Adding a number to text
The WriteLine() method needs a string as an argument. To create that string, Small Basic turns the entire argument into a string, as shown in Figure 2-4. It converts the number 12 to a string ("12") and then glues it to "Let's concatenate: 5 + 7 = " to make a new string: "Let's concatenate: 5 + 7 = 12".
Figure 2-4: Using the plus sign to join a string and a number
TRY IT OUT 2-2
Write a program to display Figure 2-5.
Figure 2-5: Making a face
Small Basic objects can have properties (or attributes) that you can change. If you change these properties, the object’s methods may give you different outcomes when you call them.
For example, let’s imagine a new object named Frog that contains two methods, Jump() and Eat(), and one property called EnergyLevel. When you call the Jump() method, Frog jumps, but each jump causes its EnergyLevel to go down. You can call the Eat() method to restore its energy. If you keep ordering the Frog to jump without feeding it, the Frog runs out of energy and can’t jump anymore. The outcome of calling the Jump() method depends on the current value of the EnergyLevel property. The property changes the state of the Frog object (whether it can jump or not). Calling Jump() at one state (when EnergyLevel is high) gives a different output than calling Jump() at a different state (when EnergyLevel is low). Poor hungry frog!
Setting and Changing Property Values
Here’s the general format for setting or changing a property of an object:
ObjectName.PropertyName = Value
For example, to make the TextWindow object output yellow text, you would enter:
TextWindow.ForegroundColor = "Yellow"
That statement changes the TextWindow object’s state: after this statement, any text printed by calling WriteLine() is displayed in yellow. But any text that has already been displayed in the text window won’t be affected. The statement tells the TextWindow object, “From this point on display text using a yellow color.”
Working with Properties
Listing 2-6 shows some ways you can put the TextWindow properties to use.
1 ' Properties.sb
2 TextWindow.Title = "Discovering Properties..."
3 TextWindow.BackgroundColor = "Yellow"
6 TextWindow.CursorLeft = 4
7 TextWindow.CursorTop = 1
8 TextWindow.ForegroundColor = "Blue"
9 TextWindow.Write("BLUE TEXT")
11 TextWindow.CursorTop = 3
12 TextWindow.ForegroundColor = "Red"
13 TextWindow.Write("RED TEXT")
15 TextWindow.CursorLeft = 1
16 TextWindow.CursorTop = 5
17 TextWindow.BackgroundColor = "Green"
Listing 2-6: Placing and coloring your text
Running this code gives you the output in Figure 2-6.
Figure 2-6: The output of Properties.sb
Now let’s walk through the code. Figure 2-7 will help you visualize what’s happening. It illustrates the text window as a rectangular grid of characters and shows the position of the cursor after Small Basic completes each statement.
Figure 2-7: Illustrating the output of Properties.sb
Line 2 sets the Title property, which tells Small Basic the title of the text window. Line 3 sets the BackgroundColor property to "Yellow" for all the upcoming text outputs. The Clear() method (line 4) tells TextWindow to repaint itself using its BackgroundColor property, which is what makes the window’s background yellow. Try removing this line from the program to see what changes in your program’s output.
Lines 6–8 set the cursor position to column 4, row 1 and set the foreground color (the text color) to blue for the next output. The Write() method at line 9 writes the string "BLUE TEXT", starting at the current position of the cursor. The Write() method is just like the WriteLine() method, except it doesn’t move the cursor to the next line after it displays the string. After this call, the cursor is at column 13 but still in row 1.
Line 11 moves the cursor down to row 3. Line 12 sets the foreground color to red, and line 13 calls Write() to display the string "RED TEXT".
Lines 15 and 16 move the cursor to column 1, row 5; line 17 sets the background color to green. This is the last statement, so the program terminates at this point (because there’s no more code to run). Because the foreground color of the text window is still set to red, the Press any key to continue... message is displayed in red on a green background.
For a complete list of colors you can use in the text window, see http://tiny.cc/twcolors/.
TRY IT OUT 2-3
Now you have a chance to go hi-tech next Valentine’s Day. Write a program that draws a card similar to the one shown in Figure 2-8, and share it with your crush. (Hint: draw the heart first with red. Then switch the foreground color to green and call Write() three times to draw the text.) Get creative with your colors and make it personal.
Figure 2-8: A Valentine’s Day heart
Computers are excellent for crunching numbers (they megabyte!) and work great as glorified calculators. Small Basic includes the four basic arithmetic operations: addition, subtraction, multiplication, and division, which are represented by +, –, *, and /, respectively. Those symbols are calledoperators because they operate on values, which are called operands. Let’s look at a few examples. These math operations will be familiar to you. Try entering these lines in the Editor:
TextWindow.Writeline(4 + 5)
TextWindow.Writeline(3 / 6)
TextWindow.Writeline(8.0 / 4)
TextWindow.Writeline(3 * 4)
TextWindow.Writeline(9 - 3)
When you run this program, each answer appears on a new line, like this:
But how would Small Basic find the result of an expression like this: 6 * 2 + 3? Does this mean multiply 6 times 2 and then add 3, which equals 15, or multiply 6 times the sum of 2 and 3, which equals 30? When an arithmetic expression contains different operators, Small Basic completes the expression using the same priority used in algebra, as shown in Figure 2-9.
Figure 2-9: The order of operations in Small Basic
So, for 6 * 2 + 3 with no parentheses, Small Basic would multiply 6 times 2 and then add 3, for a result of 15.
As in ordinary math, each left parenthesis in a Small Basic program must have a matching right parenthesis. For example, the expression (6 + 4) is valid, but (6 + (8 – 2))) isn’t valid because it has an extra right parenthesis.
To make sure you get the results you want, use parentheses to clarify the order of operations. This helps you avoid mistakes and makes your code easier to understand. For example, enter the following:
TextWindow.WriteLine((3.5 + 6.5) - (5 - 2.5))
If you placed your parentheses correctly, you should get 7.5.
Adding a single space on both sides of an operator is also a good idea. For example, the expression 5 + 4 * 8 is easier to read than 5+4*8. Although Small Basic can read two consecutive arithmetic operators, as in 3*–8, it’s best to put the negative number in parentheses, such as 3 * (–8)to make your code easy to read and avoid any confusion.
TRY IT OUT 2-4
In Lewis Carroll’s Through the Looking Glass, the Red Queen and the White Queen ask Alice to do some addition and subtraction in Wonderland. Using the WriteLine() method, create Small Basic programs to help her solve these two problems:
“Can you do Addition?” the White Queen asked. “What’s one and one and one and one and one and one and one and one and one and one?”
“I don’t know,” said Alice. “I lost count.”
“She can’t do Addition,” the Red Queen interrupted, “Can you do Subtraction? Take nine from eight.”
“Nine from eight I can’t, you know,” Alice replied very readily: “but—”
Just because a program runs doesn’t mean it’s correct. All programmers make errors at some point, especially when they write long programs. But don’t worry! You’ll make fewer errors the more you practice. Three main types of errors in programming are syntax errors, logic errors, and runtime errors; we’ll teach you how to find and fix them.
Errors pop up whenever a program breaks one of the language’s syntax rules. Examples of syntax errors include the following:
• Missing punctuation, such as in TextWindow.WriteLine("Hello), which includes a string without an ending quote
• Extra punctuation at the end of a statement
• Misspelled keywords, such as Whle instead of While
• Arithmetic operators used incorrectly, such as 5 ** 2
• Mismatched parentheses in arithmetic expressions, such as 5 * (6 - (3 + 2)
A keyword is a special word that tells Small Basic to do something, like to repeat a statement. We’ll explain each one in later chapters.
Fortunately, the minute you click the Run button, Small Basic discovers any syntax errors and describes them in an error message. The error message lists the line numbers in your source code where the errors were found (see Figure 2-10). If your program contains a syntax error, look at the line that contains the error and see if you can fix it!
Figure 2-10: An example of a syntax error
Need to find the problem fast? Just double-click the error message to jump to the line that contains the error. (Pretty awesome, huh?)
Sometimes, you might make a mistake in your program’s logic. These logic errors cause your programs to produce the wrong results. For example, if you accidentally used a minus sign instead of a plus sign, you’ve made a logic error. Your program runs normally, but the output’s incorrect!
Logic errors are called bugs, and debugging is the process we use for finding and fixing these bugs. For short programs, you might be able to locate the bugs by hand tracing, which means you read the program line by line and write down the output you expect for each step. Another common technique is to insert additional WriteLine() statements to display the output at different parts of the program. This helps you narrow down the lines where the program might have gone wrong.
Runtime errors happen after you run your program, when it experiences a problem that’s not solved in your code. For example, your user may enter bad numbers that can cause your program to stop working, or crash. You’ll discover these errors yourself when you start tinkering with Small Basic.
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. Write a program that displays your name and age, similar to the following output. Use colors to make the output fit your own style!
My name is Sandra Wilson
I am 12 years old
2. Replace the question marks in the following program with strings that give your user information about the order of an element in the periodic table. Run the program to check its output.
TextWindow.Write("?" + " is the " + "?")
TextWindow.WriteLine(" element in the periodic table.")
3. Cathy wrote the following program to figure out how much money she earned from babysitting. But there’s a problem: her program doesn’t work. Help Cathy find the bug in her program and fix it.
' This program computes my earnings from babysitting.
' Hours worked: 20
' Pay rate: $4 per hour
TextWindow.WriteLine("I earned: $" (20 * 4))
4. Write a program that creates a Christmas card similar to the one shown here. Use any colors to decorate the tree.