Introduction

Variables are an integral part of computer programming. They allow us to save results of operations and calculations temporarily in memory and then reuse the results later on.

In this chapter we shall see in detail, how variables work in Python, some of the most common errors occuring while writing variables, and naming conventions to name variables in valid, yet meaningful ways.

Creating variables

As we've seen in the last chapter on Python Basics, creating a variable in Python is an simple as deciding a name, and then typing it followed by an = equals sign followed by the value to be placed in the variable.

Unlike languages such as JavaScript, Java, C++, there is no special keyword to create a variable in Python. For example, in JavaScript we would write var x = 10 to create a variable x with the value 10. Notice the keyword var here - it's used to declare a variable in JavaScript.

Let's quickly create two variables x and y and assign to them the values 7 and 3 respectively:

x = 7
y = 3

These variables can be used just like we would normally use numbers, as is, in arithemtic operations. Consider the following snippet:

x + y
10
x - y
4
x * y
21
x + x
14
A variable represents a given value so use it just like you would normally use the value in any place.

No declaration

If you have the experience of working with another programming language such as Java, C++, then you would know that these languages have two stages of creating a variable.

The first stage is called variable declaration. In this stage the interpreter allocates some space in memory to hold the variable.

For example, consider the following Java code to create an integer variable x:

int x

It instructs the compiler to allocate some space in memory for an integer.

The second stage, which is optional, is called variable assignment. In this stage the interpreter/compiler puts a value inside the memory location reserved for that variable.

Here's how variable assignment would look in our previous Java code:

int x = 10

The part x = 10 assigns a value to the location reserved for the variable x.

Now as we just read in the section above, Python doesn't work this way:

There is no stage of declaration in Python - we have to assign a value to a new variable rightaway.

Variables can vary

As the term 'variable' suggests, a variable can vary in the course of a program.

Let's say we have a variable x with the value 10, as shown below. We can perform a couple of operations using this variable and then later on change it to some other value.

Consider the following code:

x = 10
print(x + 12) # 22

x = 30
print(x + 12) # 42

First we set x to 10, and then print its sum with the number 12. Next we change the value stored in x to 30, and perform the same print routine as we did before.

See how we changed the value of x from 12 to 30. This is what variables are - containers of data that can change during the course of a program.

Better yet, we can even change the type of value stored in a variable in Python. This feature, not available in many programming languages, is known as loose typing.

Consider the following code:

x = 10
print(x + 12) # 22

x = "Hello"
print(x + " World!") # "Hello World!"

To start with, x is an integer. However, later on it becomes a string. The type of x has definitely changed.

In the section below we understand in detail what exactly does it mean to be loosely typed and how is this feature powered in languages such as Python.

Loosely typed

In strictly-typed languages, before we create a variable we have to specify its type.

During the course of the program's execution the variable's value can definitely change - otherwise it wouldn't have been called a variable! However, its type can't change.

So for instance, if you stated that a variable x is an integer then you can only assign integers to it, not any other data type.

Python, as we know, isn't one of these languages. Rather it's a loosely-typed language.

A loosely-typed language is one where there is no restriction on changing a variable's value to another data type.

You can put any value in a variable and then later on change it to any other value of any other data type - no restrictions at all.

These languages automatically perform all the necessary optimisations and type conversions in the background for you.

Let's come back to Python and see loose typing in action:

First we assign an integer to x, then a string and finally a Boolean.

A Boolean might be something new for you - it's simply a true or false value used in conditional execution - details to come in a chapter upstream.
Because loosely-typed languages like Python, PHP, JavaScript have to perform type conversions and optimisations in the background themselves, programs written in these languages are relatively slower than their conterparts written in strictly-typed languages. However, for everyday applications the difference is almost negligible!

Variable naming rules

Naming variables effectively is a fruitful skill developers must have. Variables are imperative to programming and so is naming to variables.

In this section we'll see some rules defining how to and how not to construct variable names, in addition to some common conventions used out there for naming.

A variable's name in Python (and in almost all programming languages) can contain only the characters a-z, A-Z, 0-9 and _. Nothing else is allowed!

So for instance, all the following variable names are invalid - they would throw a syntax error.

welcome-message
x1!
main container
raining?

A syntax error is an error in the way we've written our code. It is evaluated at compile time, that is during the phase when our program is being understood by the interpreter/compiler.

Even digits are only allowed if they do not appear at the start of the variable's name.

For instance, m1 is a valid name, whereas 1m isn't, since 1 appears at the start of the name.

1m

Python has a large list of special keywords reserved for special purposes, as shown below:

Using these words as is for variables isn't allowed because it would otherwise interfere with the functionalities prescribed for these special words.

In the code blow, we attempt to create a variable pass to hold a password, however the code throws an error since pass is a reserved keyword.

pass = "15645"

In short,

A variable's name in Python can not have:

  1. A digit at the start.
  2. Any character other than a-z, A-Z, 0-9 and _.
  3. A reserved keyword, as is.

Moving on, let's now discuss some common conventions and disciplines of constructing variable names.

Variable naming tips

Suppose that you have to store a user's name in a variable. It would be really bad if you name the variable a or n or x.

A variable's name has to be descriptive

The name a doesn't tell much about what's stored in the variable. A much better name could be username, uname or even just name.

But hold on to your descriptive naming skills - you don't want never-ending names.

Variable names shouldn't be overly descriptive

Suppose we want to create a variable that stores the first name of a user. Being exceptionally descriptive we could name it thefirstnameofuser, although this would be more than the required amount of description.

We have to remain in between the scale of description - not too little, and not too much.

Sometimes it's really helpful to abbreviate long words in a variable's name given that the abbreviation seems sensible.

Abbreviate long words to short, but descriptive, character sequences.

For example, the variable name fname could go well for the first name of a user, instead of firstname. Here we've abbreviated 'first' to 'f'. Similarly, a variable to store the name of a database can be called dbname instead of databasename

But keep in mind that abbreviations don't always work well.

For instance, naming a variable that holds the name of an object's property as pname, instead of propertyname would be a complete mess. pname could mean 'property name' or 'panel name' or 'previous name'. A much better name would be propname - with the word 'property' abbreviated down to 'prop'.

When a variable's name contains more than one word, it's desirable to put a separator between the words to be able to distinguish between them easily while reading the variable, or use some sort of casing convention.

Differentiate between individual words in a variable's name using a casing convention

Let's say you have a variable questionsasked that holds the number of questions asked in a quiz program. Seeing this name doesn't rightaway tell us about the individual words in it. We have to gaze at it for a while until we realise that it says 'questions asked'.

Worse yet, in some words the name could even be misinterpreted by the reader.

The solution to this is to use a casing convention.

Some common casing conventions are as follows:

  1. camelCasing: every word's first letter is uppercased except for that of the first word. Camel casing is the casing used in JavaScript. Here are some identifier names from JavaScript: indexOf, getElementById, querySelectorAll.
  2. PascalCasing: every word's first character is uppercased. C# uses pascal casing. Some identifier names from C# are as follows: WriteLine, Readline, GetType.
  3. snake_casing: every word is lowercased and separated from the other using an _ underscore character. PHP uses snake casing. Some identifier names from PHP are as follows: array_push, mysqli_connect, str_split.

Coming back to our example, the variable questionsasked could be renamed to one of the following:

  1. questionsAsked
  2. QuestionsAsked
  3. questions_asked

Now it doesn't require much effort on our side to comprehend what exactly is the name of the variable trying to say. All the individual words are recognisable at the first glance.

But which one of these should we use?

Which convention to use?

Well you can use any of these conventions - it really is up to you which one you are comfortable with.

But, generally, it's recommended to use snake casing in Python.

Nonetheless, whichever one you choose, make sure you stick with it throughout your application. Consistency is a must!

To boil it all down, naming isn't something that has a preset list of rules that one could use to devise meaningful names.

Surely there are naming conventions out there, but the best name for a given scenario comes with:

  1. Experience - the more you code the better you become in naming.
  2. Lots of trial and error - keep on altering the name of the variable unless and until you think it communicates its purpose in the best way.

Case-sensitivity

Let's say you create a variable name, save a string value in it and then print Name.

What you will get is not the string stored inside name, but rahter an error

Why?

This is because the interpreter detects that there is no variable named Name and so raises a NameError exception.

The variable that you created was name, however the one you attempted to print was Name. There is a difference in the casing of both these names and likewise they are considered two different entities.

Variable names are case-sensitive in Python (and almost all programming languages).

That is, two variables with differently cased characters are not tantamount to each other.

In the example above, name with every character in lowercase was the variable we created. However, Name with a captial N in the beginning was one we printed. which isn't the same as name, and thereby doesn't exist in memory.

Referring to a non-existent variable raises a NameError in Python. Always take care of errors of this type.

Are the variables name and namE the same variable?

  • Yes
  • No

Moving on

In this chapter we saw a great amount of detail on variables in Python. From this point onwards our journey of exploration gets into level 2 now that we have almost half of our foundation on Python covered.