Python – Constants

A constant is a type of variable which cannot be changed. That is very helpful to think of constants as containers that contain information which cannot be changed later.
In Python, constants are usually declared and assigned in a module. Here, the module means a new file that contains variables, functions, etc; which is imported into the main file. Inside the module, the constants are written in UPPERCASE letters and the words are separated with the underscore character _

Built-in constants 

A small number of constants live in the built-in namespace. They are as follows:

Not Implemented

This constant its value is Trueif Python was not started with an option -O. See also the assert statement .


Names None and __debug__cannot be reassigned (assignments to them, even as an attribute name, cause a SyntaxError exception ), so they can be considered “true” constants.

python constants

Example of constants 

Here are some examples of using constants :

Example of constants from an external module

Create a file named with the following content:

IP_DB_SERVER  =  "" 
PORT_DB_SERVER  =  3307 
USER_DB_SERVER  =  "root" 
PASSWORD_DB_SERVER  =  "123456789" 
DB_NAME  =  "Androiddevlearn"

Create a file named with the following content:

constant import

print  "scp -v -P {0} {1} @ {2}: / {3} / {4} / {4} .sql / srv / backup" . format ( 
    str ( constants . PORT_DB_SERVER ),  constants . USER_DB_SERVER ,  
    constants . IP_DB_SERVER ,  constants . USER_DB_SERVER , 
    constants . DB_NAME )

Then run the program as follows:


When you run the program, the output will be:

scp -v -P 3307 root@ /root/webapp/db.sql / srv / backup

In the above program, there is a module file Then this are assigned constants values IP_DB_SERVERPORT_DB_SERVERUSER_DB_SERVERPASSWORD_DB_SERVER and DB_NAME. Also, there is the module file which imports the module constants. Finally, a connection line of the scp Linux command is printed using the function built into the standard Python library called format ()


Actually, constants are not used in Python. The global o module constants is used throughout Python programs.