Literals in Python

1. What are Literals in Python

Python literals refer to the fixed values contained within the Python scripts that require no computation. These literals serve as the constant values which, while in the source code, undergo no alterations. Their inherent immutability makes them the building blocks of any Python program, as they form the data required to execute complex operations.

2. Types of Literals in Python

Python literals encompass several categories, each offering unique capabilities to accommodate a wide spectrum of data types. There are 5 types of literal in Python, they are

  • Numeric Literals
  • String literals
  • Boolean literals
  • Special literals
  • Literal Collections

2.1. Numeric Literals in Python

Numeric literals in Python are immutable and represent numeric values. They are categorized into three types:

  • Integers
  • Floating-point numbers
  • Complex numbers

l. Integer literals

These are whole numbers without a decimal point and can be of different types such as binary, octal, decimal, and hexadecimal. For example, 10 (decimal), 0b1010 (binary), 0o12 (octal), 0xA (hexadecimal) are all integer literals representing the number 10.

Example:


# Decimal
dec_num = 10
print("Decimal: ", dec_num)

# Binary
bin_num = 0b1010
print("Binary: ", bin_num)

# Octal
oct_num = 0o12
print("Octal: ", oct_num)

# Hexadecimal
hex_num = 0xA
print("Hexadecimal: ", hex_num)

When you run this code, all the print statements will output "10", demonstrating that these different representations all refer to the same integer value.

Output:


Decimal:  10
Binary:  10
Octal:  10
Hexadecimal:  10

ll. Floating-point literals

These are real numbers that have a decimal point or exponent (or both). For example, 10.0, 1.5, -0.3, 0.3e5 are all examples of floating-point literals.

Example:


# Floating point
pi_approx = 3.14
print("Pi Approximation: ", pi_approx)

# Exponential representation
large_distance = 3.0e8  # represents 3*10^8, common in scientific calculations
print("Large Distance: ", large_distance)

Output:


Pi Approximation:  3.14
Large Distance:  300000000.0

lll. Complex literals

These literals are used to represent complex numbers. They have a real part and an imaginary or complex part, which is suffixed with "j". For example, in 10+3j, ‘10’ is real part and ‘3j’ is imaginary part.

Example:


# Complex number
complex_num = 3 + 4j
print("Complex number: ", complex_num)

# Accessing real and imaginary parts
print("Real part: ", complex_num.real)
print("Imaginary part: ", complex_num.imag)

Output:


Complex number:  (3+j)
Real part:  3.0
Imaginary part:  4.0

2.2. String Literals in Python

String literals in Python are a sequence of characters enclosed in quotes. They are used to represent text data in a Python program. Python supports different kinds of string literals, including:

  • Single-line strings
  • Multi-line strings
  • Formatted strings

l. Single-line strings

These are string literals enclosed within single (' ') or double (" ") quotes.

For Example:


str1 = 'Hello, World!'
str2 = "Python is fun."
print(str1)
print(str2)

Output:


Hello, World!
Python is fun.

ll. Multi-line String Literals

Python provides triple quotes (''' ''' or """ """) to define strings spanning multiple lines. For instance:


str3 = '''This is a 
multi-line string 
in Python.'''

Output:


This is a 
multi-line string 
in Python.

lll. Formatted String Literals (also known as f-strings)

Introduced in Python 3.6, these literals are prefixed with the letter 'f' and are used to embed expressions inside string literals. The expressions are enclosed in curly braces {} and are replaced with their values when the string is printed.

Example:


name = 'Alice'
str4 = f'Hello, {name}!'
print(str4)

Output:


Hello, Alice!

3. Boolean Literals in Python

Boolean literals in Python are the two constant objects True and False, which are used to represent truth values. They are the result of comparison or logical operations and are instances of the bool class, a subclass of int

True represents the value 1 and False represents the value 0.

Example:


is_active = True
is_inactive = False

print("Is active? ", is_active)
print("Is inactive? ", is_inactive)

# Outputs:
# Is active?  True
# Is inactive?  False

4. Special Literals in Python

Python's Special literals consist solely of None, used to denote the absence of value or nullity. None is a unique object of its datatype - the NoneType. It serves numerous purposes, including defining a null variable or specifying a function's absence of return value.

Example:


# A variable with no initial value
x = None

print("The value of x is: ", x)

# Output:
# The value of x is:  None

5. Literal Collections in Python

Collection literals in Python are data structures that store multiple items in a single variable. Python has four basic inbuilt collection literal types, namely:

  • Lists
  • Tuples
  • Sets
  • Dictionaries

l. List Literals

A List is a collection literal that is ordered, changeable, and allows duplicate members. It is written as items separated by commas and enclosed within square brackets [].

Example:


fruits = ["apple", "banana", "cherry"]

Output:


["apple", "banana", "cherry"]

ll. Tuple Literals

A Tuple is a collection literal which is ordered and unchangeable (immutable), and allows duplicate members. In Python, tuples are written with round brackets ().

Example:


colors = ("red", "green", "blue")
print(colors)

Output:


('red', 'green', 'blue')

lll. Set Literals

A Set is a collection literal which is unordered and unindexed, and it doesn't allow duplicate members. Sets are written with curly brackets {}.

Example:


primes = {2, 3, 5, 7, 11}
print(primes)

Output:


{2, 3, 5, 7, 11}

lV.Dictionary Literals

A Dictionary is a collection literal which is unordered, changeable, and indexed. No duplicate members are allowed. In Python, dictionaries are written with curly brackets {}, and they have keys and values.

Example:


student = {"name": "John", "age": 22, "course": "Computer Science"}
print(student)

Output:


{'name': 'John', 'age': 22, 'course': 'Computer Science'}

3. Revision Notes

  • Literals are the raw data values or constants in Python.
  • Types of Literals
    • Numeric Literals: Integer (whole numbers), Float (real numbers), and Complex (numbers with a real and imaginary part).
    • String Literals: Sequences of characters defined by single, double, or triple quotes.
    • Boolean Literals: Two truth values - `True` and `False`.
    • Special Literals: Python has one special literal - `None`, denoting the absence of value.
    • Collection Literals: Used to store collections of data and can be a List, Tuple, Dictionary, or Set.
  • Common Mistakes with Literals
    • Type Mismatch: Ensure proper type conversion when combining different types of literals.
    • Incorrect String Usage: Choose the right quotes to avoid errors.
    • Misunderstanding `None`: `None` signifies the absence of a value, not `False` or zero.

4. Quiz

1. Which literal in Python is mutable?
2. How is a string literal defined in Python?
3. How would you correctly declare a complex literal in Python?
4. What does the `None` literal denote in Python?
5. What is the output of the following code snippet?

myList = [1, 2, 3, 4]
print(type(myList))
Kickstart your IT career with NxtWave
Free Demo