When computing the difference of 41 and 12, we were able to print it above: print(41-12). However, what if we wanted to reuse the computed result in another computation? For example, Emperor Caligula reigned from 37 to 41. How much of this was from his life? Now you need to compute following stages, or subgoals:
To achieve this, we need to store a variable on the computer's memory. We want to first compute 41-12 and store it to memory. I will use to indicate this memory. We then conduct another computation: 41-37. Again, we need to store it to the memory. For clarity we call this memory so we do not confuse it with . The final operation is to conduct the division: , or simply
This storage is known as a variable. Variables store its assigned values. To separate different things we might need to store during programming, programmers give names to variables. In later stages of the program, these names are used to access and even change the value given to a variable. You may think variable as a box which has a label (its name) and some content that is stored (the value). A program can set a new value to the box or look at what it contains (without taking it out from the box.) Above, we used and as names to the variables. We stored values to them and then applied those variables in later stages of programming. Code example 2.3 illustrates how this may look like in visual programming language, Python and R. Note how we have chosen variable names which clearly communicate to us and others what the variables stores. Variable names like year of birth and age explicate what kind of thing is stored into the variable. It makes it easier to read the code and understand its purposes. As the examples show, in Python, = is used to assign a value to a variable; in R, both = and <- can be used. When using = it should be read as `assigned to' and not as `equals' There are various operations available for variables. Table 2.1 summarises some of them, both in Python and R.
Values have types. For example, above we have only worked on numbers â integers to be exact. Integers can be added together, reduced for each other, multiplied and so on. However, a number and text cannot be added together. The computation of âGaius Julius Caesar Augustus Germanicusâ + 29 is not defined. There is no numerical value for âGaius Julius Caesar Augustus Germanicusâ, and there is no textual value for 29. In a more general sense, a computer cannot count apples and oranges.
Sometimes it makes sense to try to do something with apples and oranges. For a computer to understand this in Python and R, it is the responsibility of the programmer to change the variable types. When asking the computer to calculate "five"+5, an error emerges. You must transform the textual value "five" to a number before conducting this operation. It is sometimes called casting a value. Code 2.4 shows how this can be achieved.