Variables and Identifiers in Python

What is a Variable?

Programming languages are used mainly to convert our ideas into the logic that machines can follow.

Let’s understand this with one of the best examples!

Think of vending machines that we all are aware of. Let’s say you need to buy cola and chips, you select the item from the keypad, and the machine will automatically pop the selected items for you. It is the machine. Hence it is programmed so that it remembers where the cola is placed and where the chip is.

To put it in context, this cola is the data that is stored in container A in our vending machine. You press A and the machine offers it to you. Same way variables are containers that can be used to store data. And we can call them whenever we need that assigned data.

Let’s take another example; You see two glasses filled with water of different colors.

Now, what if you want to exchange the water for another glass? Can you exchange the water directly? No, right? It will mix the water.

To do that, you need 3rd glass which can temporarily hold the water, and once the water is shifted to a temporary glass, you can easily pour the water into the empty glass. And transfer water from temporary glass to recently emptied glass.

As we saw, transferring water without a temporary glass holding water was impossible. Similarly, any program will need extra memory to hold the data. For that, we create a variable (a temporary memory) that can hold data of different types.


In simple words, these glasses are variables that store the data for us which in this case is water and we are using this variable/glasses as per our convenience in our program to accomplish some tasks.

This is what variables are used for!

Let’s try to imagine with another example.

Think of a big room with slabs all over it to place things. Now when you have to store something in that room, you use jars. That means you open a jar and put the stuff inside of it, you put a name sticker on that jar and place it on the slab.

if you have to put something else; you get another jar and put it on another corner on the slab.

Here this big room is computer memory, jar is variable, stuff is value and name sticker is identifier.

When you need the same stuff, you use the name sticker to find it.

When you want to reuse the same jar, you can empty it and refill with some other stuff.

Variables are fundamental to programming for two reasons:

  1. Variables keep values accessible: For example, you can assign the result of some time-consuming operation to a variable so that your program doesn’t have to perform the operation each time you need to use the result.
  2. Variables give values context: it acts as a context; for example, The number 28 could mean lots of different things, such as the number of students in a class, the number of times a user has accessed a website, and so on. Giving the value 28 a name like num_students (this is a variable) makes the meaning of the value clear.

Now you can change the value of the variable num_students later if required. It can be, let’s say, 32. Well, that’s the point of the variable, right? It can vary.

community = "Co-Learning Lounge"  ## Here community is variable which hold the value(i.e name) "Co-Learning Lounge"

print(community)

"""
output:

Co-Learning Lounge

"""

 

Note: Although = looks like equals to, it is an assignment operator in Python. This simply means what is on the right of this operator, is being assigned to the left variable.

e.g:

locationA = “Cola”

locationB = “Chips”

The assignment operator (=) operator takes the value to the right of the operator and assigns it to the name on the left.

Variable names are case-sensitive, so a variable named community is not the same as a variable named Community. For instance, the following code produces a NameError:

print(Community)

"""
output:


NameError                                 Traceback (most recent call last)

<ipython-input-1-ff17b64a0b48> in <module>()
----> 1 print(Community)


NameError: name 'Community' is not defined

"""

 

What are Python Identifiers?

The identifier is a name used to identify a variable, function, class, module, etc.

locationA = “cola”

locationA is identifier here.

As we mentioned this earlier in this blog that variable helps to give context to the data stored. Let’s understand it here!

num_students = 32 means variable who’s name is “num_students” holds value of 32. So we can easily know that 32 is the number of students. But what if we write it as follows,

a = 32 here variable whose name is “a” holds a value of 32. Now we don’t have any idea what is this 32 number. Weight? Age? Price of 1 L petrol (Just kidding)?

This calls for a point that the variable name should be meaningful, and while naming the variable, it has to follow some naming rules so that Python can accept the name, which we call an “Identifier” in Python. It is like we have identities. Like PAN no, Passport No, SIN, etc. All these IDentifiers have specific naming conventions.

We should be as descriptive as possible while giving names to variable.

Identifier naming conventions:

  • The identifier is a combination of alphabets in lowercase (a to z) or uppercase (A to Z), digits and underscore.
  • The identifier should ALWAYS start with a alphabets(a to z, A to Z) or Underscore but digit.
  • We should not use special characters ( #, @, $, %, ! ) in identifiers.
  • We should not use white space in identifiers.
  • Python’s reserved keywords cannot be used as identifiers (False, None, True, and)
  • There is no limit on the length of an identifier

Examples of valid identifiers:

  1. var1 ## The variable starts with a alphabet and end with a number
  2. _var1 ## A vairiable can start with a underscore
  3. _1_var ## A vairable can start witha a underscore followed by number/alphabet
  4. var_1 ## A variable can be combination of alphabets,numbers and underscores

Examples of invalid identifiers

  1. !var1 ## A variable name cannot start with a special character
  2. 1var ## A variable cannot start with a number
  3. 1_var ## A variable cannot start with a number
  4. var#1 ## A vairable cannot contain special charater ‘#’
## We can have only underscore as an identifier, it is allowed.

_ = "Co-Learning Lounge"
print(_)

"""
output:

Co-Learning Lounge

"""

Python allows us to assign multiple variables in a single statement.

Let’s see one example!

a,b,c = 1000, 2000, 3000  ## Variable assignment

print(a)
print(b)
print(a)

"""
output:

1000
2000
1000

"""

Python allows us to assign multiple variables in a single statement. The values will be assigned in the same order as we have seen in the above example.

The values are assigned in the same order which means first identifier will have first value after assignment operator as given in the example.

What if the number of values are mismatching? Means, if you try to assign two values to three variable, it will throw error. Let’s see how?

a, b = 20, 30, 50

"""
output:

ValueError                                Traceback (most recent call last)
<ipython-input-2-da5a14a6cf9b> in <module>
----> 1 a, b = 20, 30, 50

ValueError: too many values to unpack (expected 2)

"""

We can also assign some operation the same way. Have a look here:

P, Q = 20 , 10

R, S = (P+Q), (P*Q)

print(P, Q, R, S)

"""
output:

20 10 30 200

"""

Descriptive Names Are Better Than Short Names

Descriptive variable names are essential, especially for complex programs. Writing descriptive names often requires using multiple words. Don’t be afraid to use long variable names.
In the following example, the value 60 is assigned to the variable m:

m = 60

The name m is totally ambiguous. Using a full word makes it a lot easier to understand what the code means:

minutes = 60

minutes is a better name than m because it provides more context. But it still doesn’t convey the full meaning of the code. Is 60 the number of minutes it takes for a process to finish, or is it the length of a webseries? There’s no way to tell.

The following name leaves no doubt about what the code means:

minutes_per_hour = 60

When you read the above code, there’s no question that 60 is the number of minutes in an hour. minutes_per_hour takes longer to type than both the single letter m and the word minutes, but the payoff in clarity is massive.
Although naming variables descriptively means using longer variable names, you should avoid using excessively long names. A good rule of thumb is to limit variable names to three or four words maximum.

We have discussed about variables and understood some the conventions that are used for better results and efficient coding. Variables will be useful for us while learning other important things.

We are going to know more features of these when we implements these while learning next more advanced concepts.