Python Literals

Python literals are data items that have a fixed value. These values are represented directly in the code and are used to assign a value to variables or constants. Python supports several types of literals, which can be categorized into the following:

1. Numeric Literals

2. String Literals

3. Boolean Literals

4. Special Literals

5. Collection Literals

1. Numeric Literals

Numeric literals are used to represent numbers. They can be classified into three types:

Integer literals: Whole numbers without a decimal point.

      ‣ Example: 100, -45, 0

Float literals: Numbers with a decimal point.

      ‣ Example:3.14, -0.001, 1.0

Complex literals: Numbers with a real and an imaginary part.

      ‣ Example: 2 + 3j, -5j

integer_literal = 100
float_literal = 3.14
complex_literal = 2 + 3j

print(integer_literal) # Output: 100
print(float_literal) # Output: 3.14
print(complex_literal) # Output: (2+3j)

2. String Literals

String literals are sequences of characters enclosed within single (' '), double (" "), or triple quotes (''' ''' or """ """). They can represent a single character or a sequence of characters.

• Single-line strings: Enclosed in single or double quotes.

      ‣ Example: 'Hello', "World"

• Multi-line strings: Enclosed in triple quotes.

      ‣ Example: '''This is a multi-line string'''

Example:

single_line_string = "Hello, Python!"
multi_line_string = '''This is a
multi-line string.'''

print(single_line_string)
print(multi_line_string)

Output:

Hello, Python!
This is a
multi-line string.

3. Boolean Literals

Boolean literals represent one of two values: True or False. These are used in logical operations and conditional statements.

Example:

isActive = True
isDeleted = False
print(isActive) # Output: True
print(isDeleted) # Output: False

4. Special Literal

Python has one special literal, None. It represents the absence of a value or a null value. None is often used to signify that a variable has no value assigned to it.

Example:

result = None
print(result) # Output: None

5. Collection Literals

Python provides literals for several built-in data types that can hold collections of values.

List literals: Enclosed in square brackets [].

      ‣ Example: [1, 2, 3], ['apple', 'banana', 'cherry']

Tuple literals: Enclosed in parentheses ().

      ‣ Example: (1, 2, 3), ('a', 'b', 'c')

Dictionary literals: Enclosed in curly braces {} with key-value pairs.

      ‣ Example: {'name': 'Alice', 'age': 25}

Set literals: Enclosed in curly braces {}, similar to dictionaries but without key-value pairs.

      ‣ Example: {1, 2, 3}, {'a', 'b', 'c'}

Example:

list_literal = [1, 2, 3, 4, 5]
tuple_literal = ('a', 'b', 'c')
dictionary_literal = {'name': 'Alice', 'age': 25}
set_literal = {1, 2, 3, 4}

print(list_literal) # Output: [1, 2, 3, 4, 5]
print(tuple_literal) # Output: ('a', 'b', 'c')
print(dictionary_literal) # Output: {'name': 'Alice', 'age': 25}
print(set_literal) # Output: {1, 2, 3, 4}