Naming Variables![[next]](../../img/ltp/arrow-next.gif)
Giving things names is an important conceptual and intellectual tool, not just for programming but for problem-solving in general.
In your code, when you create a name for something, it is called a variable. A variable is a place for the computer to remember something. You, the programmer, get to choose the names of your variables and tell the computer what to put in them. Variable names may contain letters, numbers, or underscores, but they may not start with a number.
|
1
2 3 4 5 var myFavoriteNumber = 25 var myFavoriteColor = "Blue" printp(myFavoriteNumber) printp(myFavoriteColor) |
Click to run the code. |
This example create two variables, one named myFavoriteNumber, which holds a number, and another variable named myFavoriteColor, which holds a string. You can refer to the thing a variable is holding by just using the variable's name. Simple and powerful!
Exercise: Undeclared variable. What happens if you try to refer to a variable that has not been declared anywhere?
Putting var in front of your variables when you first name them is optional but considered good practice. It helps readers of your code see that your variable is being defined for the first time in a particular place, so they don't have to go hunting through your code.
Variables can contain strings or numbers, as in the example above, or they can contain other "types" of data that we will learn about later. If you have variables containing numbers, you can perform mathematical operations on them.
|
1
2 3 4 5 6 7 8 var x = 30 printp(x*30) x = (x + 10) / 4 printp(x) var y = 400 printp(x-y*y/x) x = y + 10 printp((x-10) == y) |
Click to run the code. |
The mathematical operators +, -, *, and / have the same meaning your 2nd grade teacher taught you. And just like in math class, you can use ()'s to group together mathematical expressions, as in line 3.
Note the important difference between a single =, which assigns value to a variable, and double ==, which checks whether two things are equal to each other. This is why you use == when testing request.path to serve different pages, and not =.
The single = takes the value to the right and puts it in the variable on the left.
Note that in an assignment statement like x = y, the variable x gets assigned the current value of y. No permanent relationship between x and y is created, and if y changes value later, it doesn't have any effect on x.