Python Variables Complete Tutorial

In this section, we will learn what variables are and how to use them in Python.

What is a Variable in Python? (Define Variable)

Python programs work with data! These data are stored in memory when the program is running.

The memory is a compartmentalized area, and each part has its own address!

Now we use variables to keep track of where each piece of data is stored when a program is running.

Think about a variable as a pointer to a memory location. Using this variable, we can put data into that memory space or retrieve the data.

Note: For those of you that are coming from statically typed languages such as C, C++, Java, and C# be aware that variables in Python don’t have their own memory spaces! They are literally just a pointer to another memory location where something is stored there. As you might remember for objects, they were saved in an area of the memory called Heap and the variables just took their memory address and hence variables were just a pointer to actual objects. Now in python, everything is object and everything store in the Heap area. So a variable just points to a memory address where a data currently is there.

Python Declare and Initialize Variable

The process of creating a variable and linking it to a value is called declaration and initialization.

Rules of declaring variables in Python

The most important rule to remember when declaring a variable is that right where the declaration is happening, a value should be assigned as well. Or in another word, declaration and initialization happen at the same time.

Python Variable Declaration Syntax:

variable_name = value

First start with a name for the variable and then comes the assignment operator `=` and after that we put the value we want to link the variable to it.

Example: declaring variables in Python

age = 20

name = "John Doe"

Here, the first variable name is `age` and is pointing to the value 20. This means the value 20 is now stored in the memory and the `age` variable is just pointing to that memory location.

The second variable is named `name`. The value this variable is pointing to is a string and that is `John Doe`. This means the value `John Doe` is stored in the memory and the `name` variable is pointing to that location.

Python Variable Assignment and Reassignment

A variable, as the name suggests, is capable of pointing to a memory location first and then change and point to another memory location! This is called variable reassignment.

Example: assigning to variables in Python

age = 20

name = "John Doe"

name = age

In this example, the `age` variable is pointing to the memory location where the value 20 is. In the next statement, the `name` variable is pointing to the memory location where the value `John Doe` is.

But look at the third statement! Here, the `name` variable is reassigned!

The `name` variable at this statement is now pointing to a memory location that the `age` variable is pointing as well.

This means both `name` and `age` variables are pointing to the same location.

Note: For those of you that are coming from statically types languages, be aware that basic types are immutable and so if there are multiple variables pointing to one basic data type and one of the variables changed that value, a new value will be produced and stored in another memory location and only the variable that changed the value will point to the result value in the new memory location. So the other variables are still pointing to the old value in the first memory location.

Python Variable Reading

The process of taking the value that a variable is pointing at is called variable reading.

In order to take the value of a variable, we need to put the variable in any location other than on the left side of the assignment `=` operator.

Note: when using a variable on the left side of the assignment `=` operator, it will act as the receiver and that means we can make the variable to point to another memory space.

Example: reading from variables in Python

sum_res = 10+10

result = sum_res

Here, the `result` variable is pointing to the same memory address that `sum_res` variable does. This is because we put the `result` variable on the left side of the assignment operator (So it acts as the receiver) and the `sum_res` variable on the right side of the assignment operator (So it acts as the giver).

Python Variable Naming Conventions

There are a couple of rules that you need to follow when creating variables in Python:

  • The name of a variable can contain letters, numbers and underscore `_` and we can start the first letter of a variable with either letters or underscore but not numbers!
  • We can’t use white space between a variable! For example: `full name` is wrong because it contains a white space.
  • Python has a set of reserved keywords that do a set of tasks. We can’t use those reserved keywords as the name of variables!
  • Use a descriptive name for variables in python. A name that helps you remember what was the purpose of the target variable.

For example: age, fullName, student_name etc.

But names like: s_n or sfaga or rtw2, these are confusing names and although you can use them but you shouldn’t! Because at later times there’s a high chance that you’ll forget what was the purpose of the variable.

Reserved Words in Python List:

False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Python Built-in Functions

Other than the reserved keywords mentioned above, there is a set of built-in functions in Python that should not be used as the name of variables.

Note: using the name of these built-in functions won’t cause an error but it will override the behavior of these functions, which means we will lose the access to the built-in function after using their names for other purposes.

abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

FAQ:

Is Python Case Sensitive?

Yes! And this means a variable name like `age` is different from a variable like `Age` or `AGE`.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies