Lesson 2
The Basic Elements
Chapter 6: Variables
Why variables?
So, why do you need variables to name your objects?
Variables give you a better level of abstraction. When writing programs, we encourage a higher-level of abstraction.
Compare the two pieces of code below.
In this first version, the code looks compact. But looking closer, you might find it hard to understand at first glance. You will have to try to work out what the programmer intends.
- What is
n
? What isx
? - What is the mysterious number
42
? It appears again in Line 8! - What is this
n < 5
thing? - We have repeated
"Please enter a number: "
and"Incorrect."
twice. What if we need to change the text in the future?
1 2 3 4 5 6 7 8 9 10 11 |
|
This second version below is a bit longer. However, it is more self-explanatory. Another plus is that you can change any values easily, without worrying about where else it occurs in the main code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Can you see the difference? With a higher-level of abstraction,
- You can easily reuse your objects in other parts of your code, rather than referring to them using their values or memory location (e.g.
user_message
,secret_number
andincorrect_message
are used multiple times in the code above) - Your code is more readable (assuming you gave your variables meaningful names)
- Your code will be easier to maintain. For example, you can easily change the values of
secret_number
andmax_guesses
in the future, rather than trying to hunt every single occurrence of them in your code. Need to write your guessing game in a different language? Just change the values ofuser_message
,correct_message
, etc. without touching your main algorithm.