Python variables

A variable is a name given to a location in memory. So when you create a variable, you actually reserve some space in the memory and you can store any useful information in that memory location. So we can think of a Python variable similar to a container that stores some useful stuff.


Naming convention to create Python variables

You can choose any name of a variable you like. However, there are certain rules to keep in mind while creating a Python variable. These rules are as follows.

  1. A variable name must start either with an alphabet or an underscore( _ ).
  2. The variable name must not contain any whitespace or special characters(@, ^, %, etc).
  3. The variable name must not be similar to a reserved keyword in Python.
# Valid variable names
my_var123 # Valid
_Myvar2   # Valid
my_var_   # Valid

# Invalid variable names
1a       # Invalid
[email protected]   # Invalid
my var   # Invalid

Creating variables in Python

Now that we have learned the naming convention, it’s time to create variables. In Python, a variable is created once you assign some value to it. Assigning a value simply means storing some value or data to it. This is done using the assignment operator ( = ).

my_var = 10

The code written above does the following tasks.

  1. It creates a variable named my_var.
  2. Reserves some space based on the type of value in the memory.
  3. Stores value 10 at that memory location.

The operand left to the operator = is the name of the variable and the operand right to the operator = is the value stored in the variable my_var.

Note: Like other programming languages, there is no need to declare a variable in Python. Declaration and assignment both take place at the time of assigning value to the variable.

Now let’s create some more variables and display them.

# A program to create variables in Python
my_var1 = 10
my_var2 = "Programmers Portal"
my_var3 = 10.23

print(my_var1)
print(my_var2)
print(my_var3)

Output:

10
Programmers Portal
10.23

Assigning values to multiple variables at a time

Python allows us to assign a single value to multiple variables at a time.

# A program to demonstrate multiple assignments in Python

# Assign value 10 to each variable
var1 = var2 = var3 = 10

print(var1)
print(var2)
print(var3)

Output:

10
10
10

Note: You can also assign different different values to each variable using a single assignment operator. Refer below example:

# A program to demonstrate multiple assignments in Python

# Each variable holds different value
var1,var2,var3 = 10,'Programmers Portal',20

print(var1)
print(var2)
print(var3)

Output:

10
Programmers Portal
20