Let's Make Robots!

Newbie’s guide into programming - 00000110 - Variables and constants. General understanding.

Helps newbies to learn how to program

Here I will try to explain general idea behind variables, one of the essentials of programming. And I will try to use following analogy: a glass of water.

Here 'GLASS1' is variable name, you can refer to the variable by its name. Variable value is the content of a variable. In our example the value of GLASS1 is water. If we've put beer into the GLASS1 instead of water, that would mean that the value of GLASS1 has changed, but you still can refer to GLASS1.

Now let's expand our knowledge. Say, we want to build an imaginary robot for mixing coctailes. It will take two glasses as input and output one glass. It will have following program:

OUTPUT_GLASS = INPUT_GLASS1 + INPUT_GLASS2

This program simply would take contents of input glasses and pur them into output glass. The program here refers to glasses by their names, though the result of program will depend on actual values of input variables. If you pour iced tea into INPUT_GLASS1 and sirup into INPUT_GLASS2, you should have a nice drink in your OUTPUT_GLASS. But if you would use beer and vodka instead, you will get a 'Screwdriver' as output. What's interesting, is that we have absolutely same program in both cases! Can you see how important are variables for programming?

Now we will step off our example and add another important property of variables: type. It basically governs what type of values can be stored in a variable. Type can be a numeric, boolean, or string. These are just a few general types. Types have different names in different programming languages. The most important point of using variables is that they are allowed to be changed thruout program execution.

 

Constants are almost the same as variables, they have name, value and type. The only difference is that the value of a constant cannot be changed, i.e. It is constant. Let's modify our mixing program.

Constant ICE_GLASS = 'ICE'

OUTPUT_GLASS = INPUT_GLASS1 + INPUT_GLASS2 + ICE_GLASS

Here in first line we declare that there will be another glass named ICE_GLASS and it will always contain ice. And the second line does mix two input glasses and also adds ice to the mix.

In the next chapters we will see how variables are used.

See other chapters of this series here.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Im just getting into robotics and so far my biggest challenge has been variables... in particular, reading the sensors that detect walls. This was a great way to explain it, thank you!