Chapter 6: Variables

Why variables?

face Josiah Wang

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 is x?
  • 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
n = 1
x = int(input("Please enter a number: "))
while x != 42 and n < 5:
    print("Incorrect. ")
    x = int(input("Please enter a number: "))
    n = n + 1

if x == 42:
    print("Correct")
else:
    print("Incorrect. Game over.")

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
user_message = "Please enter a number: "
incorrect_message = "Incorrect."
correct_message = "Correct."
game_over_message = "Game over."

secret_number = 42
max_guesses = 5
num_of_guesses = 1

guess = int(input(user_message))

while guess != secret_number and num_of_guesses < max_guesses:
    print(incorrect_message)
    guess = int(input(user_message))
    num_of_guesses = num_of_guesses + 1

if guess == secret_number:
    print(correct_message)
else:
    print(incorrect_message + " " + game_over_message)

Can you see the difference? With a higher-level of abstraction,

  1. 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 and incorrect_message are used multiple times in the code above)
  2. Your code is more readable (assuming you gave your variables meaningful names)
  3. Your code will be easier to maintain. For example, you can easily change the values of secret_number and max_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 of user_message, correct_message, etc. without touching your main algorithm.