Literals In Python

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:

Numeric Literals:

Integer literals: These represent whole numbers, such as 123, -456, or 0.

Example:

# Declare variable with Integer value
age = 55

Floating-point literals: These represent decimal numbers, such as 3.14, -0.001, or 2.0.

Example:

# Declare variable with Float value
totalAmount = 40.5

Complex literals: These represent complex numbers, such as 3 + 4j or 1 - 2j.

Example:

# Declare variable with Complex value
equationVar = 3 + 4j  

String Literals:

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.

Boolean Literals:

True: Represents the boolean value True.

Example:

# Declare variable with `Boolean` value
isStudent = True;

False: Represents the boolean value False.

Example:

# Declare variable with `Boolean` value
isStudent = False;

None Literal:

None: Represents the absence of a value or a null value.

Example:

# Assigning `None` to a variable
noneVar = None;

Sequence Literals:

List literals: Enclosed within square brackets [], representing ordered collections of items.

Example:

# 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.

Example:

# 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.

Example:

# Declare variable marks with `set` literal
marks = {45, 25, 66, 88, 50}

Dictionary literals: Enclosed within curly braces {}, representing collections of key-value pairs.

Example:

# Declare variable `dictObject` with `dict` literal
dictObject = {'name': 'Alice', 'age': 20, 'isStudent': True}

Literal for Bytes and Byte Arrays:

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.

Literal for Ellipsis:

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.