Declaring single variables

In Python, a variable is created during assignment. Python is type inferred — therefore there is no need to explicitly define a variable’s type. It can simply be created by naming it and then assigning any value irrespective of the type to it.

Example

For instance, let’s name a variable moving_average. To save or assign a value to it, we will use the assignment operator (=) followed by the said value.

moving_average = 10.2
name_of_language = "Python"
main_languages = ['Python', 'JavaScript', 'C++', 'Java', 'GO']
Declaring values in Python


Here, the variables are moving_average, name_of_language, and main_languages, and each variable has a different type of value. 10.2, “Python”, and [‘Python’, ‘JavaScript’, ‘C++’, ‘Java’, ‘GO’] are literals. In Python, literals refer to a specific and fixed value of a variable at any instant.

Literals, in Python, refer to a specific and fixed value at any instant.

Note: We can not use reserved keywords to name variables. The following table shows the list of reserved keywords found in Python 3.12.0.

False

assert

continue

except

if

nonlocal

return

None

async

def

finally

import

not

try

True

await

del

for

in

or

while

and

break

elif

from

is

pass

with

as

class

else

global

lambda

raise

yield

Reassigning Variables

When there is a need to update a variable, they can be reassigned values easily as well

Example

Suppose the moving_average changes to 10.5, Python allows changing the value of a variable by simply reassigning it again.

moving_average = 10.5
print(moving_average)
Reassigning variables in Python

Declaring Multiple Variables

We can define multiple variables in one line by following a comma separated syntax. Python also provides for the ease of saving the same value in more than one variable.

Example

For example, let’s create two variables, called mean and median, and save 5 and 7 in them, respectively. Let’s also create sorted_list and sorted_list2 and save [‘1’, ‘2’, ‘3’, ‘4’] in both of these variables.

mean, median = 5, 7
print(mean, median)
sorted_list = sorted_list2 = ['1', '2', '3', '4']
print(sorted_list)
print(sorted_list2)
Declaring multiple variables in Python