teach-ict.com logo

THE education site for computer science and ICT

3. Naming variables

It is good practice in programming to give variables a sensible name that will help explain its purpose.

What you should not do is put spaces into a name even if the language allows it, as it can be confusing and it is too easy to mistype it later.

Single letter

A single letter variable is often used to just count. For example the code below is using 'x' to count in a loop.

    Line 10:      FOR x = 1 TO 10       // x is being used to count
    Line 11:         ..... some code               
    Line 12:      NEXT x               // increment x and go back to the FOR line  

Don't worry about what a loop is - that is covered later. But the point is that 'x' has no other use than to count and so does not need a complicated name.

Longer names

If the variable has a specific purpose, then give it a relevant name. For example, the code below is asking for an age to be input, so naming the variable 'age' makes it obvious what the it contains

    Line 10:      age = input("Please enter your age:") 
    Line 11:      output "Your age is " + age              

Using capitals

Some variables are better to have two words in the name to describe it. In which case capitalise the first letter of each word. For example

    Line 10:      FirstName = "Laura"
    Line 11:      SecondName = "Bradshaw"              

Using capitals makes it much easier to read than firstname or secondname.

Alternative method

If you don't like to use capitals then a good alternative is to use underscore to separate the words in the name. For example

    Line 10:      first_name = "Laura"
    Line 11:      second_name = "Bradshaw"              


Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: How to name a variable