One reason we use variables is that they allow us to easily reuse values in different parts of our code.
When we reuse a value, it will appear in multiple places in our code. Re-typing that value becomes tedious, which leads to errors, and without a variable name, it becomes unclear as to what the value represents. It may also be unclear as to what that value is meant to represent.
Let’s take a look at the following piece of code. Here we have a number that we reuse in order to make some calculations:
847595593392818109495 847595593392818109495 * 2 847595593392818109495 / 4
Rather than writing the same number over and over again, we can save it to a variable named
my_number = 847595593392818109495 my_number * 2 my_number / 4
You may be thinking, “But what if my variable name is longer than the value it stores? What’s the point of a variable?”
When we use a value without assigning it to a variable, that’s known as hardcoding. While it’s sometimes faster to initially hardcode values in your program, in the long run you’ll run into trouble — especially if you need to change what those values are.
The last time we built our game, we repeated ourselves a lot. Instead of writing out the pattern for each tile, let’s save the types of terrain we want to use to a set of variables that we can use across the board.
Replicate the previous design by making each variable equal to one of the following:
As you enter your choices, what do you notice about the board that changes?
How was this process different from the last exercise? Did variables make this process more efficient?