Tutorial 2: Elements of Code
Comments are ignored by the computer when it runs a program, but they are important for people to understand what your code is doing. Because code often takes a lot of effort to read and understand, it is important that you document your code as you write it. Comments allow you to leave notes about your code so that (a) other people can understand what it does, and (b) you can understand what your code does when you come back to it. Processing supports two different styles of comments; single line comments and multiple line comments. In the Processing editor, you can tell that something is a comment because it is coloured grey.
Single Line Comments
Single line comments are denoted by two forward slashes:
// This is a single line comment
All of the text following the two forward slashes on the same line are part of the comment and ignored by the computer when it runs the program.
Notice that there are no spaces between the forward slashes. If you put a space between the forward slashes, like this
/ /, it does not indicate a comment and will cause an error, i.e., the computer will interpret the first of these forward slashes to mean that you want to divide a number by another and then raise an error when it can't find any numbers.
A single line comment doesn't have to be the only thing on a line, you can put code before the forward slashes and the computer will execute it. This can be very handy for making a quick note about a line of code without making you're program longer, e.g.:
size(200, 200); // Set the size of the window to be 200 x 200 pixels
Naturally, it is possible to have many single line comments within a program, allowing blocks of comments to be formed, e.g.:
// This is a single line comment. // This is another single line comment. // This is a third single line comment.
This is one way to write long comments in a piece of code, i.e., you don't have to include all of your comment on one line. It is also important to note that you can "comment out" one or more lines of code using this technique so that they aren't executed, e.g., the following code will be ignored:
// size(200, 200); // background(0); // Fill the window with black // line(50, 50, 150, 150); // Draw a diagonal line across the window
Notice that it doesn't matter if there is already a single line comment in the code.
Multiple Line Comments
Multiple line comments are denoted by a forward slash followed by an asterisk (star) at the beginning of the comment, and an asterisk followed by a forward slash at the end of the comment.
/* This comment runs over multiple lines of code. This style of comment can be handy for writing long descriptions about what a sketch does. */
Another use for multiple line comments is to "comment out" long pieces of code, e.g., when debugging a program. The following code would be ignored because it has been commented out with a multiple line comment:
/* size(200, 200); background(0); // Fill the window with black line(50, 50, 150, 150); // Draw a diagonal line across the window */
Notice that it is OK to have single line comments within a multiple line comment like this. Be careful when using this technique to comment out code that there aren't any existing multiple line comments in the code that you're trying to comment out, as these will cause problems, e.g.:
/* size(200, 200); /* Fill the window with black */ background(0); line(50, 50, 150, 150); // Draw a diagonal line across the window */
Notice that the multiple line comment ends with the first
*/ not the second one, so the lines
line(50, 50, 150, 150); are still going to be executed by the computer, however, the second
*/ will cause Processing to report an error because it will try to interpret this as a multiplication sign followed by a division sign. (We'll get to the mathematical signs used in Processing soon.)
As noted above, you may prefer to use single line comments for both descriptions and commenting out code. There is no requirement to use multiple line comments when writing your code.
There is one other style of comment that you may see in Processing code. It is used for officially documenting code and it is a variant of the multiple line comments we've already seen. Documentation comments begin with a forward slash followed by two asterisks, i.e.,
/**, and ends (just like a normal multiple like comment) with an asterisk followed by a forward slash
The important thing about documentation comments is that while they are ignored by the computer when running the program, they can be extracted by other programs to produce documentation about the code. Documentation comments include descriptions of parts of code and often include special terms like
@returns that indicate who wrote the code, when they first wrote it, and aspects of what the code does etc. When you use code written by other people, especially libraries, they will often come with documentation that has been generated this way.
Both Processing.js and Peep define a small number of directives that may appear at the beginning of a sketch to affect how the browser displays the sketch and/or the sketch code (in the case of Peep). We'll introduce you to these directives as we continue through the unit of study.
For the moment, the only directives that you'll need to know about is the
@peep sketch and
@peep sketchcode directives that tell Peep that you want it to either automatically run sketch code that you have embedded in a Portfolio post or show the code but allow someone to run the code by clicking on "show sketch". You'll need this for the first assignment, but we'll post more information about using the portfolio system soon. In the meantime, here's an example of using the
@peep sketch directive:
And an example of using the
@peep sketchcode directive:
Expressions and Statements
An expression is like a phrase in English: an expression always has a value, determined by evaluating its contents. Some expressions can achieve complex results, but an expression can be as simple as a single number. Here are some examples of some expressions, with their values:
| Expression Value | | 5 5 | | 122.3 + 3.1 125.4 | | ((3 + 2) * -10) + 1 -49 | |"jack" + " & " + "jill" "jack & jill" | | 6 > 3 true | | 54 < 50 false |
A set of expressions create a statement, the programming equivalent of a sentence. Every statement ends with a terminator, the programming equivalent of a full stop / period. In the Processing language, the statement terminator is a semicolon
;. You have to use a semicolon at the end of every statement that you make in Processing.
There are different types of statements, e.g., a statement can declare a variable, assign a value to a variable, run a function or construct an object.
int x; // Declares a new variable called x x = 102; // Assigns the value 102 to the variable x size(200, 200); // Runs the size() function // The following statement does three things: // 1. It declares a new variable called img; // 2. It constructs a PImage object; and, // 3. It assigns the PImage object to the img variable PImage img = new PImage();
Functions are a fundamental building block in computer programming, they are fragments of code that achieve a significant task. Processing comes with many functions already written, which makes it much quicker and easier to achieve common tasks. In Processing, functions allow you to draw shapes, set colours, calculate numbers, and to execute many other types of actions.
A function's name is often a single word followed by parentheses, i.e., round brackets, that contain any data that the function needs to accomplish its task. The data to be passed to a function is included as a comma-seperated list of elements between the parentheses. When data is passed to a function in this way it is called a set of parameters. Some functions have no parameters and others have many.
Parameters have to be listed in the same order that the function expects them to be in. For example, the
size function takes two parameters. The first sets the width of the display window and the second sets the height:
// Set the size of the display window to 200 x 200 pixels size(200, 200);
Some functions appear to take different numbers and types of parameters. (In fact, there are multiple functions with the same name that take different numbers of parameters, but we can ignore this detail for the moment.) For example, their are multiple versions of the
background function that take different numbers of parameters.
// This version of the background function has one // parameter. It sets the grey value for the background // of the display window in the range of 0 (black) to // 255 (white) background(102); // This version of the background function has three // parameters. It sets the colour value for the // background of the display window using RGB (or HSB) // colour components background(127, 191, 15);
Code that you want a computer to execute needs to be properly formatted for the computer to be able to understand what you want it to do.
The Processing language is case sensitive; it differentiates between uppercase and lowercase characters such that a variable called
name is considered to be different from one called
Name. The same is true for functions, so the following code will cause an error because no function with the name
Size exists (the correct name is
Size(200, 200); // Generates an error when run
Consequently, you must be careful to match the case of functions and variables in your code. You can check the formatting of functions and variables built-in to Processing in the on-line reference. The authors of Processing have been careful to follow the following convention when naming functions:
- If the variable or function is a single word, use only lowercase characters, e.g.,
- If the function contains multiple words, use lowercase for the first word and then capitalise the first letter of each subsequent word, e.g.,
Following a coding convention like this is definitely good practice and you should try to follow the convention above when naming your own variables.
Whitespace characters include spaces, tabs, and new lines. In Processing, you can use as many whitespace characters as you want between code elements. Using space to arrange your code neatly can improve the readability of your code. Whitespace characters cannot be included in variable or function names, so
hello kitty is not a valid variable name. A common convention is to use the underscore (
_) character in place of the whitespace, e.g.,
In the desktop Processing development environment, the console is located below the editor in the main window. (It is also where any errors are displayed in red if there are problems running your code.)
In the on-line version of Processing that we're using on this web site for tutorials etc. the console is an area that is displayed only when you print to it, or when an error is encountered.
Printing to the Console
When a computer executes code, it performs operations at a rate too fast to watch it as it runs. A simple way to see what is happening when your code runs is to print information to the console. The functions
println() can be used to display messages and data in the console area while a program is running.
Enter the following code in the editor to the right to see the console area appear when you run it:
The blue square that appears when you run this sketch is your display window. The black area at the bottom of the screen is the console, where you can see the message that we printed.
The difference between the functions
println() is that
print() prints just the text that you provide, whereas
println() prints the text and then moves the cursor to the next available line, ready for the next thing to print.
Enter the following n the editor to the right and compare what is printed to the console with the previous example:
size(200, 200); background(0, 0, 255); print("Hello World!"); print("This is the console."); println();
This second version of the program prints the two sentences "Hello World!" and "This is the console." on the same line with no space in-between them. Notice that the last line of this example calls
println() without any parameters. We do this to force the console to display. Try removing this line from the editor, close the console (using the cross in the top-right corner of the console area) and running the code again. The console area won't open because it stores the results from calls to
print() until a
println() is received to reduce the amount of printing that it has to do.
Typically, you'll just want to use
println() to print a message or some data on its own line, however, if you have a lot of data that you want to format in a specific way then
print() can be more appropriate. Just remember to finish printing out your data with a final call to
println() to ensure that the console is updated.