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.
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.
var x = 10 to create a variable
x with the value
10. Notice the keyword
Let's quickly create two variables
y and assign to them the values
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:
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
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
x = 10 assigns a value to the location reserved for the variable
Now as we just read in the section above, Python doesn't work this way:
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
10, and then print its sum with the number
12. Next we change the value stored in
30, and perform the same print routine as we did before.
See how we changed the value of
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.
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.
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.
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
_. 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.
m1 is a valid name, whereas
1m isn't, since
1 appears at the start of the name.
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"
A variable's name in Python can not have:
- A digit at the start.
- Any character other than
- 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 doesn't tell much about what's stored in the variable. A much better name could be
uname or even just
But hold on to your descriptive naming skills - you don't want never-ending names.
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.
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
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.
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:
- PascalCasing: every word's first character is uppercased. C# uses pascal casing. Some identifier names from C# are as follows:
- 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:
Coming back to our example, the variable
questionsasked could be renamed to one of the following:
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:
- Experience - the more you code the better you become in naming.
- 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.
Let's say you create a variable
name, save a string value in it and then print
What you will get is not the string stored inside
name, but rahter an error
This is because the interpreter detects that there is no variable named
Name and so raises a
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 the same variable?
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.