Register Login

Literal in Python

Updated Mar 28, 2022

Every student must have gone through constants during their school days mathematics classes. Those constants values remain fixed throughout the mathematics problem. Almost all programming language caters to the same concept also. Storing values in the RAM through program requires the concept of Literals. This topic will cover all about Python literals, its types, and its uses.

What is a literal in python?

Literals in Python are notations or concepts that help in representing fixed values of a source code. These are raw values that act as constants. Again, they also help fill the variable (RAM locations) with specific values that will be used within the Program. If we consider an initialization statement g = 28 then, that 28 will be out literal, more precisely integer literal. Due to dynamic typing, Python can understand the type of literal the program is using or the variable has been declared.

Types of Literals:

Python caters to a wide variety of literals. These are:

String literals:

We can create a string literal by writing a text (a group of characters) surrounded by the single(' '), double(" "), or triple quotes (''' ''' or """ """). Single quotes and double quotes are the most commonly used ones. While triple quotes allow writing multi-line strings or display in the desired way. Also, often triple quotes alone help in creating multi-line comments.

Example:

a = 'gaurav ray'
# using double quotes
b = "Gaurav Roy"
# multi-line keeping the format same
c = '''Gaurav
        Ray
            TechWriter'''
print(a)
print(b)
print(c)

Output:

Character Literals 

also come as a part of String literals in Python. It is because single quote and double quotes are not different in Python as in C or C++. But the difference between character literal and string literals is: if the single or double quotes contain only one character, then we call it character literal. Whereas, if the single or double quotes contain multiple characters within their pairs, we call it strings.

Example:

# using single quotes
a = 'r'
# using double quotes
b = "s"
print(a)
print(b)

Output:

Special String Literals: 

Some characters are not legal to put in the string sections. These characters or strings are specially treated by preceding them with a backslash. They are popularly known as escape sequences.

Example:

txt = "We are the so-called \"Anonymous\" \n from the gangs of Karlos."
msg = "We write \t hacking codes using \t Python"
esc = "Using escape sequence \\n \\t \\\\ \\v etc. "
print(txt)
print(msg)
print(esc)

Output:

Numeric Literals: 

In numeric literals, we can only add digit, and these are immutable. There are three different types of numeric literal. These are integer, float, and complex. Python users widely use each of these literals.

Example:

a = 0b101	 #Binary Literals  
b = 100	 	#Decimal Literal   
c = 0o24 	#Octal Literal  
d = 0x12d 	#Hexadecimal Literal    
	
#Float Literal  
float_1 = 20.7   
float_2 = 3.7e8  
	
#Complex Literal   
a = 10+3.14j  
print(a, b, c, d)  
print(float_1, float_2)  
print(a, a.imag, a.real)

Output:

Integer, Decimal, Hexadecimal, Binary, Literal:

In computer science, an integer literal is one of the types of numeric literal. It contains both positive and negative values, including zero. We cannot add any fractional numbers or rational numbers. The integer literal in the octal number system starts with '0o.'

Example:

# integer literals
# Binary Literals

x = 0b101

# Decimal Literal

y = 80
# Octal Literal
z = 0o34

# Hexadecimal Literal

p = 0x19f
print(x, y, z, p)

Output:

Float Literal:

In Python, a floating-point literal denotes a real number that includes both the integer part with the fractional part. We can represent a floating-point literal in the decimal number system as "theNum=123.123."

Example:

# Float Literal
a = 88.8
b = 50.0
print(a, b)

Output:

Complex Literal:

We can write a complex number for integer literal in the structure of a+bj where 'a' denotes the real part and 'b' denotes the imaginary part of the complex number. We can represent a numeric literal defining a complex number as:  theNum = 9+9j.

Example:

p = 5 + 9j
# real part is 0 here.
q = 3j
print(p, q)

Output:

Boolean Literals:

In Python, we can add only two values for a Boolean literal. These are either "true" or "false." We can represent them as

"theVar1=True
theVar2=False."

Example:

p = (1 == True)
q = (1 == False)
r = True + 8
s = False + 9
print("p is", p)
print("q is", q)
print("r:", r)
print("s:", s)

Output:

Literal Collections:

We can denote the literal collection as a syntactic expression format that evaluates to an aggregate type, such as a list, array, or Map. There are different languages apart from Python that supports literal collections.

Example:

List = ['Robin', 345,764.987, 'Salim']    
thelist = [76, 'Driv']    
print (list)    
print (list + thelist)

Output:

List Literals:

We can create a List literal by using square brackets "[]." This list can hold items of various data types. We can separate the values stored in List by a comma "," The list literal is mutable.

Example:

# List literals
number = [1, 2, 3, 4, 5]
name = ['Arjun', 'Raj', 'Sulekha', 4]
print(number)
print(name)

Output:

Tuple Literals:

A tuple literal is an expression that represents a Tuple as a collection of various data-type. We can separate the values by a comma "," and surrounded by parenthesis "()." A tuple also includes data just as lists. The tuples are immutable, and we cannot add new elements to them, or we cannot delete any entity from the tuple. We can represent the tuple as "theTuple=(5, 6, "pfb", 3.14)."

Example:

# Tuple literals
even_number = (1, 8, 16, 24)
odd_number = (13, 5, 9, 7)
print(even_number)
print(odd_number)

Output:

Dictionary Literals: 

Dictionary holds data in the "'key'; 'value'" format. We can create a dict literal by surrounding it with a key-value list within "{}"; then we can separate the key from its value with an ":" and we can separate the key: value pair with commas (,). To write an empty dict, we can only use the curve brackets "{}." We can save various types of data in the dictionary literals. Dictionaries are mutable.

Example:

# Dict literals
thevegetables = {'p': 'potatoes', 'q': 'quince', 'r': 'radish'}
information = {'name': 'Abir', 'age': 22, 'ID': 22}
print(thevegetables)
print(information)

Output:

Set Literals:

In Python, a set can hold unordered and non-duplicate data. Every element in the set literal is unique. We can specify the set literal as having several items. We have two alternatives when it comes to forming a set in Python. It is typical to pass an iterable to set(). We can also use the syntax of Python for set literals, {}. But both methods will return the set. A set literal is immutable.

Example:

# Set literals
alphabets = {'a', 'e', 'i', 'o', 'u'}
names = {"Abir", "Jaduza", "Shyam"}
print(alphabets)
print(names)

Output:

Special literals or None literals: 

In Python, we can add only one special literal, "none." Python users use this literal to indicate that we have not created a particular field. When we print a variable where we did not assign a value to it, Python will print "None" as the output. If we consider the value 'None' with anything other than this value, it will return a "False."

Example:

# Special literals
specialliteral = None
print(specialliteral)

Output:

Conclusion:

Literals play a critical role in terms of RAM and storage or handling different iterative operations and decision-making operations. Without the concept of literals, a programming language will not be able to handle bits and any other character sets within the application. So, programmers should have a clear idea of the literals and which one is associated to what value type.


×