Python Literals

Literals in Python refer to the data that is given in a variable or constant. Literals can be numbers, characters, or any other data type that has a fixed value. In Python, there are several types of literals that you can use in your programs. Understanding these literals is essential as they form the basic building blocks of any Python program.

Types of Python Literals

Python supports various types of literals, which can be broadly categorized into the following:

1. String Literals

String literals are sequences of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Triple quotes are generally used for multiline strings.

Code Example


# Single and Double Quote Strings
string1 = 'Hello, World!'
string2 = "Python Programming"

# Multiline String
multi_line_string = '''This is a 
multiline string.'''

print(string1)
print(string2)
print(multi_line_string)
            

Output

Hello, World! Python Programming This is a multiline string.

2. Numeric Literals

Python supports three types of numeric literals: Integer, Float, and Complex.

Code Example


# Integer Literal
integer = 100

# Float Literal
float_number = 10.75

# Complex Literal
complex_number = 3 + 4j

print(integer)
print(float_number)
print(complex_number)
            

Output

100 10.75 (3+4j)

3. Boolean Literals

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

Code Example


is_python_fun = True
is_sun_cold = False

print(is_python_fun)
print(is_sun_cold)
            

Output

True False

4. Special Literal: None

Python includes a special literal called None, which represents the absence of a value or a null value. It is often used to indicate that a variable is empty.

Code Example


value = None
print(value)
            

Output

None

5. Collection Literals

Python supports several collection literals like:

Code Example


# List Literal
list_example = [1, 2, 3, "Python"]

# Tuple Literal
tuple_example = (1, 2, 3, "Python")

# Dictionary Literal
dict_example = {'a': 1, 'b': 2}

# Set Literal
set_example = {1, 2, 3}

print(list_example)
print(tuple_example)
print(dict_example)
print(set_example)
            

Output

[1, 2, 3, 'Python'] (1, 2, 3, 'Python') {'a': 1, 'b': 2} {1, 2, 3}

Literals in Python are a fundamental part of writing code. They represent constant values and are used to assign data to variables. Understanding the different types of literals, such as strings, numbers, booleans, and collections, is crucial for coding effectively in Python.