What are Python literals?

Home » Python » What are Python literals?

Table of Contents

Introduction

In Python, writing the fixed values directly into the code is Python literals. These are constant values which represent data in Python program.

We assign Python literals of various types to variables or use them directly in expressions. Let’s breakdown different types of literals in Python.

1. String literals

Single, double or triple quotes can enclose these sequence of characters.


"Hello, World!"  # Double-quoted string literal
'Python'         # Single-quoted string literal
'''This is a multi-line string'''  # Triple-quoted string literal

2. Numeric literals

Numeric literals represent numbers and can be integers or floating-point numbers.

(i) Integer literals

It can be positive or negative whole number.


42      # Decimal integer literal
-100    # Negative integer literal
0x2A    # Hexadecimal literal (base 16)
0b101   # Binary literal (base 2)
0o52    # Octal literal (base 8)

(ii) Floating-point literals

It can be in decimal or in a scientific notation.


3.14    # Floating-point literal
2.0     # Another floating-point literal
1.5e2   # Scientific notation (1.5 * 10^2)

3. Boolean literals

These represent the truth value in Python. True and False


True    # Boolean literal representing truth
False   # Boolean literal representing falsehood

4. Special literals

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


None    # Special literal representing "no value"

5. Collection literals

(i) List literals

It is defined using [ ] brackets and can contain any type of object.


[1, 2, 3, 'Python']  # List literal

(ii) Tuple literals

It is defined using ( ) and can contain any type of object.


(1, 2, 3)  # Tuple literal

(iii) Set literals

It is defined using { } braces and contains unique elements.


{1, 2, 3}  # Set literal

(iv) Dictionary literals

You can define it using { } braces and it can contain key value pairs, additionally it can also contain any object.


{'name': 'John', 'age': 30}  # Dictionary literal

Conclusion

Literals in Python are direct representations of constant values in the code while they are crucial for initializing variables, defining data structures, and performing operations in a program.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *