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.
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 in Python are immutable and represent numeric values. They are categorized into three types:
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
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
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
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:
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.
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.
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!
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
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
Collection literals in Python are data structures that store multiple items in a single variable. Python has four basic inbuilt collection literal types, namely:
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"]
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')
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}
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'}
myList = [1, 2, 3, 4]
print(type(myList))