BlogsDope image BlogsDope

Python Constants and Literals

Jan. 2, 2021 PYTHON 5996

In this post, we will learn about the constants and literals in Python.

Constants:

​As the name suggests, constant is a type of variable whose value can’t be changed. 
We can think constants as a box to store balls. Once the balls are placed in the box, they can’t be replaced.

Assigning value to a constant in Python:

In python, constants are usually declared and assigned in a different module from the main module. Here, the module is a new file containing variables, functions, etc. which is imported to the main file.

Declaration and assigning values to the constants:

Create a module named constant.py:
PI=3.14
GRAVITY=9.8

Create a main file main.py:

import constant as cons
print(cons.PI)
print(cons.GRAVITY)

Output:

​3.14

9.8

In the above program, firstly we created a constant.py module file. After that, we assigned the constant value 3.14 and 9.8 to PI and GRAVITY respectively. Then, we created a main.py file and imported the constant module. After this, we print the values of PI and GRAVITY.

Rules of naming constants:

  1. Constant 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:
    Codes_Dope
    codes_dope
    CODES_DOPE
    _codes_dope7
    
  2. Constant name should not start with a digit.
  3. If we want to create a variable name having two words, we should use underscore to separate them. For example:
    MY_NAME
    CURRENT_SALARY
    
  4. Generally, the constants value are declared using capital letters. This is done to differentiate them from variables.
    PI
    G
    MASS
    SPEED_OF_LIGHT
    TEMP
    
  5. No other special character (!,#,^,@,$) is used except underscore(_) for declaring a constant.
  6. We should create a name that makes sense. For example, GRAVITY makes more sense than G. It makes code easy to understand.

​Literals:

Literals are defined as raw value or data given in a variable or constant.
For example:
a=57
b=57.9
c="Hello World"
d=57+2j

Here 57, 57.9, "Hello World", 57+2j are considered as literals.

Literals are of five types:

  1. Numeric Literal.
  2. String Literal.
  3. Boolean Literal.
  4. Literal collections.
  5. Special literals.

Numeric Literals:​

​Numeric literals are immutable (unchangeable) and they are of three types:
  1. Integer.
  2. Float.
  3. Complex.

Integer:

Both positive and negative numbers including zero, with no fractional part. For example: 125
a = 0b1000 #Binary Literals
b = 100    #Decimal Literal 
c = 0o561  #Octal Literal
d = 0x45f  #Hexadecimal Literal
print(a,b,c,d)

Output:

​8 100 369 1119

Here, we have assigned integer literals into different variables. Here, a is binary literal, b is a decimal literal, c is an octal literal and d is a hexadecimal literal. But when we print the variables, all the literals are converted into decimal values.

Float:

​These are real numbers having both integer and fractional parts.
a = 10.6 
b = 5.5e2
print(a,b)

Output:

10.6 550.0

10.6 and 5.5e2 are floating-point literals. 5.5e2 is expressed with exponential and is equivalent to 5.5 * 102.

Complex:

The numerals will be in the form of a+bj, where 'a' is the real part and 'b' is the complex part of the number.
a=5+3j

#real part is zero here
b=8j 
print(a.real,a.imag)
print(b.real.b.imag)

Output:

5.0 3.0 

0.0 8.0 

we use real literal (a.real) and imaginary literal (a.imag) to create real and imaginary parts of the complex numbers, respectively.

String Literals:

A string literal is a sequence of characters surrounded by quotes. We can use single, double, or triple quotes for a string. By using triple quotes we can write multi-line strings or display it in the desired way.
#in single quote
a='CodesDope'

#in double quotes
b=''CodesDope''

#in triple quotes”
c='''Codes
	Dope'''
print(a)
print(b)
print(c)

Output:

CodesDope 

CodesDope 

Codes

    Dope

Character literal:

It is a type of string literal. In this a single character is surrounded by single or double quotes.​

a='b'
c="d"
print(a)
print(c)

Output:

​b

d

​Boolean Literals:

​A Boolean literal can only have any of these two values: True or False.
a=(0==False)
b=(0==True)
c=5-False
d=True+7

print(a)
print(b)
print(c)
print(d)

Output:

True 

False 

8​

​In python, True value is represented by 1 and False value is represented by 0.

In above program, a is true and b is false because 0 is equal to False. 

Similarly, we can use the True and False in numeric expressions as the values.

Value of c is 5 because false value is equal to 0. So, 5-0=0. Value of d is 8 because True value is equal to 1. So, 1+7=8.   

Literals Collection:

There are 4 different types of literals collection:

  1. List literals.
  2. Tuple literals.
  3. Dict literals.
  4. Set literals.

List Literals:

List contains items of different data types. The values stored in List are enclosed within square brackets([]) and are separated by comma (,). Lists are mutable.
roll_nos=[5,6,7,8,'invalid']
fruits = ["apple", "mango", "orange"]

print(roll_nos)
print(fruits)

Output:

[5, 6, 7, 8, 'invalid'] 

['apple', 'mango', 'orange']

Tuple Literals:

A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each element is separated by the comma(,). It is immutable (unchangeable).
number = (1,2,3,4) 
names=('Jack', 'John', 'Pam') 
  
print(number) 
print(names) 

Output:

​(1, 2, 3, 4) 

('Jack', 'John', 'Pam')

Dictionary Literals:

​Dictionary stores the data in the key-value pair. It is enclosed by curly-braces ‘{}‘ and each pair is separated by the commas(,). We can store different types of data in a dictionary. Dictionaries are mutable.
student_1={'name':'Jack','roll_no':5,'age':18}
student_2={'name':'Pam','roll_no':25,'age':19}

print(student_1)
print(student_2)

Output:

​{'name': 'Jack', 'roll_no': 5, 'age': 18} 

{'name': 'Pam', 'roll_no': 25, 'age': 19}

Set Literals:

Set is the collection of the unordered data set. It is enclosed by the {} and each element is separated by the comma(,). 
Set has no duplicate elements.
alphabets={'a','b','b','c'}
numbers={1,2,3,4}

print(alphabets)
print(numbers)

Output:

​{'a', 'c', 'b'} 

{1, 2, 3, 4}

Here, we can see that the order of alphabets set is altered and the duplicate value of 'b' is not considered in the set. 

Special Literals:

​Python contains one special literal (None). ‘None’ is used to define a null variable.
None is when compared with anything else other than None, it returns False.
None is used to specify that the field has not been created.
balance = None
print(balance) 

Output:

​None

Difference between variables, constants and literals:

Variables
Constants
Literals
A variable is a named location used to store data in the memory.
A constant is a type of variable whose value cannot be changed.
Literals are defined as raw value or data given in a variable or constant.
Mutable
Immutable
Mutable and Immutable both (depends on the type of literal)
For example:
a=10
Here, a is the variable.
For example:
PI=3.14
Here, PI is the constant.
For example:
b="Hello" 
Here, "Hello" is the literal.

Yeah! we finished this concept.

Now move to the next chapter.


Liked the post?
Editor's Picks
0 COMMENT

Please login to view or add comment(s).