Select Page

Variables in Python: Types, Rules, Conventions, and a lot!

In this tutorial, you’ll learn about one of the most used terms in programming, Variables. If you’re familiar with basic mathematics, then this is the exact same concept.

Python Variables

Let’s see a quick example of code without any variable. Here I’ll print the results of some simple math operations on two numbers, 2 and 3. Notice how messy it is.

why variables important - part 1
why variables important – part 1

Okay, that’s good! Now, what if I want to apply the same set of operations on two different numbers, say 10, 20? Oh no! I’ve to change six 2’s and six 3’s, that is a total of 12 changes in a 6 line of codes! Think about a thousand lines of code, where you’ve to spend your entire day to find out where the changes are needed! It’s a nightmare, isn’t it?

In every programming language, and even in math, the concept of variable saves you here. When you use some values like 2 and 3 in the above code, Python creates an object for each of the values. That value is stored somewhere in the memory (RAM). To make your life easy, you can name that part or object. Then whenever that name is used anywhere in the code, Python will use the value stored against that name. It’s like a container containing some products and then labeling that container.

The process is to declare some value (in the memory) and then labeling it with a suitable name. Not declaring a variable and then assigning some values to it. Remember this line, it’ll be necessary within a minute.

Now let’s rewrite the previous code with variables.

variables make writing programs easy
why variables important – part 2

As you can guess, the structure of a variable is name, followed by a single equal sign (=), followed by the value. Shortly, name = value

Variable types in Python

In many other programming languages, you need to declare the type of variable depending on what type of data you’ll store in it. For example, int first = 10; float second = 20.5; . These are called statically typed languages, and you can’t store a different type of data with these variables.

Python is a dynamically typed language. So you don’t need to define the type of variables. You can even assign one type of data to a variable and later reassign another type of data to the same variable! Here’s what I mean:

python variable is not limited to assigning only one type of data
Variable type can be changed

Notice that you’re not limited to assigning only numbers to a variable. Rather, any datatype is supported.

Assign Values to Multiple Variables at Once

Remember one thing, you don’t assign values to a variable, rather you assign variable to values. The heading term is used by convention, maybe because that is how most other languages store values.

To assign multiple values at once to multiple variables, list all the variable names to the left side and all the values to the right side. There should be an equal number of values and variables. You’ll understand the examples more when learning deeply about data types of Python.

first, second, third = 10, 20.5, 'Hello, World!'

num1, num2, num3 = [100, 150, 200]

first_name, last_name = ('S. M.', 'Fahim')

Assigning One Value to Multiple Variables

As told before, Python first stores the value in memory, and then you assign a name to that location. So if you want, you can assign more than one name for that one location. Hence, using multiple names for a single value does not consume more memory. You can check this with Python built-in id( ) function.

python id function shows whether variables are taking different memory locations or the same one
id() function

Object References and Garbage Collection

We’ll try to understand what’s going on under the hood of this block of code, which will help us to understand how Python works: (The code is executed on REPL, e.g. Python IDLE, command-line, terminal, etc.)

object reference and garbage collection in python
overview
  • REPL executes each command instantly. Here, you don’t need the print function to display a result. Just hit enter after each command and it will be executed.

In the first line, the interpreter stores the value 1000 in memory and labels it with the name a, i.e. a is referencing or indicating to that storage.

variable assignment in python

Next, in b = a, interpreter labels the storage of a by b. In other words, now b is referencing a and a is referencing 1000. Hence, a and b both are referencing to 1000.

multiple variable assignment to a single value

The next command is b = 1111. Now the interpreter stores 1111 in the memory and labels it with b, hence, b is referencing 1111. But wait, b was already referencing 1000 and now it’s referencing 1111? How? As b can’t reference to 2 different locations or values at once, hence, the new command overrides the old one. As a result, now only a is referencing to 1000 and b to 1111.

reference to different variables

The last command is a = ‘Hi’. The value for a is overwritten and a is now referencing to ‘Hi’.

garbage or orphaned value

Oh no! The value 1000 is still there in the memory and no one’s referencing to it! Hence, the value 1000 or the memory for it is no longer accessible. Python will eventually notice that this part of memory is inaccessible, and will free that memory automatically so that the memory can be used for other tasks. In computer science, this process is called Garbage Collection.

final variable assignment result

This is the final result.

Join Facebook Group

Public Group

A group optimized for learning purposes. Track your progress by joining a unit

Follow on Quora

Public Space

Best place to ask questions! Join the built-in community to get help from others

Rules and Convention of Naming Variables

What are the valid variable names? What is not acceptable? Are there any good practices of naming variables? Let’s see!

Rules:

  • Can only contain alphanumeric characters and underscore: a-z, A-Z, 0-9, and _
  • The name cannot start with a number
  • Variable names are case sensitive: num, Num, NUM, all are different variable names

This set of rule is common for every programming language. But here’s the twist:

  • Python 3 supports all Unicode characters as a part of a variable name. Just don’t start the name with a number and don’t use any special character (~`[email protected]#$%^&*()-=+{[}]|\;:'”,<.>/?) within it (because they are used as operators, hence, contain special meaning).

Here’s a list of valid variable naming. For Unicode characters, I used google translate.

variable naming python
Valid variable naming in Python

As you can see, not all of the names are very readable. There are a few most commonly used methods of constructing multi-word variable names. They are:

  • Pascal Case/ CapWords: Every word is capitalized, i.e. the first letter of every word is uppercase
    • Example: NumberOfStudentsApplied
  • Camel Case: Same as Pascal, but the first word is not capitalized
    • Example: numberOfStudentsApplied
  • Macro Case: Every letter is capitalized and words are separated by underscores
    • Example: NUMBER_OF_STUDENTS_APPLIED
  • Snake Case: Every letter is in lowercase and words are separated by underscores
    • Example: number_of_students_applied

Convention

If everyone uses one single construction method for naming variables, then you can easily detect which name stands for what object type. Python’s official PEP 8 – Style Guide for Python, contains all the naming conventions.

  • Snake Case should be used for functions and variable names
  • Pascal Case should be used for class names

I’ll soon scrap the PEP-8 and list the most important rules for writing better Python code. But first, you must learn the basics of Python.

Reserved Words or Keywords in Python

There are some special words that are occupied by Python. That means you can’t use them as variable or object name. Those words help you write Python code properly. All of the keywords will be discussed in a separate tutorial.

As of Python 3.10, there are total 35 reserved keywords in Python. They are:

Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield
Python Reserved Keywords

Recommended Reading

Mind Sharing It?
Join Facebook Group

Public Group

A group optimized for learning purposes. Track your progress by joining a unit

Follow on Quora

Public Space

Best place to ask questions! Join the built-in community to get help from others