constants in python

 

Python Constants

Hello Learners, In this tutorial, you will learn about Python constants and their use cases.

Python Constants

A constant is a type of variable whose value cannot be changed.

It is helpful to think of constants as containers that hold information which cannot be changed later.

You can think of constants as a bag to store some books which cannot be replaced once placed inside the bag.

Assigning value to constant in Python

In Python, constants are usually declared and assigned in a module.

Here, the module is a new file containing variables, functions, etc which is imported to the main file.

Inside the module, constants are written in all capital letters and underscores separating the words.

Declaring and assigning value to a constant

Create a constant.py:

1
2
PI = 3.14
GRAVITY = 9.8

Create a main.py:

1
2
3
4
import constant
 
print(constant.PI)
print(constant.GRAVITY)

Output

3.14
9.8

In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally, we print the constant value.

NoteIn reality, we don’t use constants in Python. Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment.

Rules and Naming Convention for Variables and constants

Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:

1
2
3
4
snake_case
MACRO_CASE
camelCase
CapWords

Create a name that makes sense. For example, vowel makes more sense than v.

If you want to create a variable name having two words, use underscore to separate them. For example:

1
2
my_name
current_salary

Use capital letters possible to declare a constant. For example:

1
2
3
4
5
PI
G
MASS
SPEED_OF_LIGHT
TEMP

Never use special symbols like !, @, #, $, %, etc.

Don’t start a variable name with a digit.


No comments:

Post a Comment