Variable
What is a Variable?
In Python, a variable acts as a container for storing data values. Unlike other programming languages, in Python, you don’t need to declare a variable’s type, the interpreter infers the type based on the assigned value.
Naming Conventions
Names of variables in Python can be made up of letters (a-z, A-Z), underscore (_), and numbers(0-9), but can’t start with a number. Moreover, Python is case-sensitive, meaning myvar
and Myvar
will be treated as different variables.
Declaring Variables in Python
In Python, variables are declared by using the assignment operator =
. The variable name is on the left side of =
and the value to be stored is on the right side.
Let’s declare a variable myVar
and assign it the value 10
.
Dynamic Typing
Python is dynamically typed, which means you can change the type of value assigned to a variable even after the variable has been declared.
You can verify this as follows:
In the above example, we first assigned an integer value to myVar
and then a string value. We used Python’s built-in type()
function to ascertain the data type of the value currently stored in myVar
.
Assigning Multiple Variables
Python allows you to assign values to multiple variables in one line:
In this example, x will be “Apple”, y will be “Orange”, and z will be “Grapes”.
Python also enables you to assign the same value to multiple variables in one line:
Here, all three variables (x, y, z) are assigned the value “Orange”.
Deleting Variables
In Python, you can delete a variable using the del keyword:
In the above example, after deleting the variable myVar
, when we try to print myVar
, it raises a NameError because myVar
is no longer defined.
To Wrap-up, understanding the concept of variables is fundamental in Python as it plays an essential role in storing data which can be manipulated through the course of your code.