Learning Python Part-8: Python Variables and Python Constants

It is not possible every time for programmer or user to provide input values to be used in program for some operations. This approach is fine when we are working in interactive mode or testing some small programs.

However, in realtime scenarios, most of the times we need to provide and store the values in memory and are used later at the time of executing instructions.

Python Variables:

Variables acts a container that holds data which can be changed later throughout programming.

For example, 

num = 4

(in above example, “num” is variable that holds value 4 as data and = is an assignment operator )

We can assign multiple variables with different values as below

a = 2
b = 6.6
c = “Python”

Or another simple way, 

a, b, c = 2, 6.6, ”Python”

Also same value can be assigned to multiple variables as below

x = y = z = ”python”

As you may have notice in above examples, value assigned to a variable, can be integer or float or string and others which we will talk about in upcoming posts.

Python Constants:

A constant is a type of variable whose value cannot be changed. In Python, constants are usually declared and assigned on a module. In modules, constants are written in all capital letters and underscores separating the words. 

Module generally means a file containing variables, functions, classes and methods which is imported to another python program. This is done for the purpose of code reusability.

Below is the example of creating a module file and loading this module in another python program.

Create a constant.py and add below content to it

PI = 3.14
GRAVITY = 9.8 

Now create a new file test.py and add below code to it. Make sure module (constant.py) that we import is in same directory location as that of new file.

import constant


So if you notice here, in this new file we imported previously created module (constant.py). And when we execute print for value of PI and GRAVITY from constant module, automatically values associated with these constant are loaded.

Output will be:


Leave a Reply