Python Variables

What is a variable in Python?

The variable in Python is a name given to the memory location containing the value. We can also say that a variable is a kind of identifier. The identifier identifies an entity uniquely in a program during the time of execution of a program. Function names, class names are other kinds of identifiers. In this tutorial, let’s see how to create Python variables.

Rules for naming an Identifier

As Python variables are a kind of identifiers, the rules for naming an identifier applies to variables as well. Let’s see what are the things to remember when naming Python variables.

  • The name of the Python variables should start with a letter or underscore. Examples: var,_var
  • A digit cannot be the first letter of a variable name.
>>> 1var=10
  File "<stdin>", line 1
    1var=10
       ^
SyntaxError: invalid syntax
  • Except for the first letter of a variable name, the remaining letters can be lower case characters(a-z), uppercase characters(A-Z), underscore(_) or digit(0-9).
  • The white space or special characters like (!,$,%,@,#,&,*) must not be part of the Python variable name.
>>> var name =10
  File "<stdin>", line 1
    var name =10
           ^
SyntaxError: invalid syntax
  • Python variables must not be the same as the reserved word. Reserved words or keywords are defined with predefined meaning and syntax in the language. Check the list of Python keywords here.
  • Python variables are case sensitive. For instance, var and Var are considered two different variables.
>>> var=10
>>> Var=5
>>> var,Var
(10, 5)

Declaring Python variables and assigning value to it

Creating a Python variable is easy. We can create a variable whenever it’s required and it’s not required to declare a variable before using it. The variable is declared when we assign a value to it. To create a variable we just have to mention the name of the variable on the left side and value have to assigned to the variable on the right-side separated by an equal operator. The equal operator assigns the value to the variable.

variable_name = value

Unlike other programming languages, in Python, we don’t need to mention the type of the variable explicitly while creating it.

>>> var=10
>>> type(var)
<class 'int'>
>>> var='abc'
>>> type(var)
<class 'str'>

When we assign the value 10 to the variable ‘var’, the type is ‘int’, and the type is ‘str’ when we assign the value ‘abc’. Hence we can say that Python infers the type of the variable based on the value assigned to the variable.

Referencing an Object

Since Python is an object-oriented language, every data belongs to a specific type of class. Let’s see an example:

>>> print('abc')
abc

Python creates a string object and displays it to the console. We can check the data type by using a built-in type function.

>>> print(type('abc'))
<class 'str'>

A variable in Python is a symbolic name that refers or points to an object. In other words, in Python, the variable name represents the objects.

var1=10

The variable ‘var1’ refers to an integer object.

Python Variables

When you assign the same value to another variable in Python, then both variables refer to the same object.

Python Variables

We can check this programmatically by printing the memory address of the variables. The id() function returns the memory address of a variable. Print the id() of both variables to make sure that, both variables refer to the same address.

var1=10
var2=10
print(id(var1),id(var2))
1672861632 1672861632

Instead of creating another integer object, here we are referring to the same object using the different variable names. Let’s assign a new value to the variable ‘var2’ and see what happens.

var1=10
var2=10
print(id(var1),id(var2))
var2=15
print(id(var1),id(var2))

The variables ‘var1’ and ‘var2’ point to different memory locations now.

Python Variables

1672861632 1672861632
1672861632 1672861712

Python efficiently manages memory, when we use the same variable to hold different values.

Object Identity

In Python, an object identifier uniquely identifies each object. The built-in function id() identifies the object identifier. Python makes sure that no two objects have the same identifier.

var1=10
var2=10
print(id(var1),id(var2))
var2=15
print(id(var1),id(var2))
1672861632 1672861632
1672861632 1672861712

When we assign the same value to two different variables, it creates a single object and both variables refer to the same object. That is why we get the same identifier when printing the id() of both variables.

When we assign a different value to the variables, it creates two different objects and hence we get two different outputs.

Examples for variable names

As we have seen already, there are rules to create a variable name. Let’ see some examples of valid variable names.

var=10
Var=10
vAr=10
VAR=10
_var=10
v_ar=10
var_=10
_var_=10
_v_a_r_=10
var1=10
v1ar=10
print(var,Var,vAr,VAR,_var,v_ar,var_,_var_,_v_a_r_,var1,v1ar)
10 10 10 10 10 10 10 10 10 10 10

Even though all the above variable names are valid, it is always recommended to have a meaningful name for a variable. It makes the code easy to read when the variable name is descriptive. Even the multi-word variable names are acceptable. We can create multi-word variables using the below methods:

Camel case

Each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation.

Examples: employeeId, nameOfTheEmployee, ageOfTheEmployee

Pascal case

It’s the same as the camel case except that the first letter is also capital.

Examples: EmployeeId, NameOfTheEmployee, AgeOfTheEmployee

Snake case

Here we use an underscore(_) to separate the words.

Examples: employee_id, name_of_the_employee, age_of_the_employee

Assigning values to multiple Python variables

Python even supports assigning values to multiple variables in a single statement. We can assign:

  • a single value to multiple variables.
  • different values to multiple variables.

Assigning single value

a=b=c=5
print(a,b,c)
5 5 5

Assigning different values

Python variables are assigned in the order of the values.

a,b,c=5,10,15
print(a,b,c)
5 10 15

Error

If the number of values and variables did not match, then we will get an error.

a,b,c=5,10,15,20
print(a,b,c)
Traceback (most recent call last):
  File "sample.py", line 1, in <module>
    a,b,c=5,10,15,20
ValueError: too many values to unpack (expected 3)

Reference

Translate ยป