In Python, literals are the representations of fixed values within the source code.
They are used to express values of various data types directly in code.
Here are some common types of literals in Python:
Integer literals: These represent whole numbers, such as 123, -456, or 0.
# Declare variable with Integer value age = 55
Floating-point literals: These represent decimal numbers, such as 3.14, -0.001, or 2.0.
# Declare variable with Float value totalAmount = 40.5
Complex literals: These represent complex numbers, such as 3 + 4j or 1 - 2j.
# Declare variable with Complex value equationVar = 3 + 4j
Single-quoted strings: Enclosed within single quotes ' ', such as 'hello' or 'Python'.
Double-quoted strings: Enclosed within double quotes " ", such as "world" or "Programming".
Triple-quoted strings: Enclosed within triple single quotes ''' ''' or triple double quotes """ """, allowing multi-line strings.
True: Represents the boolean value True.
# Declare variable with `Boolean` value isStudent = True;
False: Represents the boolean value False.
# Declare variable with `Boolean` value isStudent = False;
None: Represents the absence of a value or a null value.
# Assigning `None` to a variable noneVar = None;
List literals: Enclosed within square brackets [], representing ordered collections of items.
# Declare variable marks with `list` literal marks = [45, 25, 66, 88, 50]
Tuple literals: Enclosed within parentheses (), representing ordered collections of items (similar to lists) but immutable.
# Declare variable marks with `tuple` literal marks = (45, 25, 66, 88, 50)
Set literals: Enclosed within curly braces {} or by using set([]), representing unordered collections of unique items.
# Declare variable marks with `set` literal marks = {45, 25, 66, 88, 50}
Dictionary literals: Enclosed within curly braces {}, representing collections of key-value pairs.
# Declare variable `dictObject` with `dict` literal dictObject = {'name': 'Alice', 'age': 20, 'isStudent': True}
Bytes literals: Enclosed within b'' or B'', representing sequences of bytes, such as b'hello'.
Byte array literals: Similar to bytes literals but mutable, created using bytearray() function.
Ellipsis: Represented by ..., often used as a placeholder or marker in code.
These literals allow us to represent different types of values directly in our Python code, making it easier to work with data and expressions.