Python – Literals

In Python, literals are used to represent fixed values in code. They are constants that can be assigned to variables or used directly in expressions. Python supports several types of literals, including numeric literals, string literals, boolean literals, and special literals.

Numeric Literals

Numeric literals are used to represent numeric values. Python supports different types of numeric literals:

  • Integer Literals: Integer literals are whole numbers without a fractional part. They can be represented in decimal, binary, octal, or hexadecimal format. For example:
x = 10        # decimal literal
y = 0b1010    # binary literal
z = 0o12      # octal literal
w = 0xA       # hexadecimal literal
  • Float Literals: Float literals represent real numbers with a fractional part. They are written with a decimal point or in scientific notation. For example:
a = 3.14      # decimal float literal
b = 2.5e2     # scientific notation (2.5 * 10^2)
c = 1.23e-4   # scientific notation (1.23 * 10^-4)
  • Complex Literals: Complex literals represent complex numbers with a real and imaginary part. They are written in the form a + bj, where a and b are real numbers and j represents the imaginary unit. For example:
d = 2 + 3j    # complex literal
e = 4j        # complex literal with no real part

String Literals

String literals are used to represent sequences of characters. They can be enclosed in single quotes (') or double quotes ("). For example:

name = 'John'      # single-quoted string literal
message = "Hello"  # double-quoted string literal

Python also supports triple-quoted strings, which can span multiple lines. They are useful for writing long strings or preserving the formatting of text. For example:

paragraph = '''
This is a multi-line
string literal.
'''

Boolean Literals

Boolean literals represent the truth values True and False. They are used to perform logical operations and control the flow of programs. For example:

is_raining = True
is_sunny = False

Special Literals

Python has two special literals: None and Ellipsis.

  • None: None is used to represent the absence of a value or a null value. It is often used as a placeholder or to initialize variables. For example:
result = None
  • Ellipsis: Ellipsis is used to represent a placeholder in slicing operations. It is commonly used in combination with the slice() function. For example:
numbers = [1, 2, 3, 4, 5]
sliced_numbers = numbers[1:4:Ellipsis]

In conclusion, literals in Python are used to represent fixed values in code. They include numeric literals, string literals, boolean literals, and special literals. Understanding and using literals correctly is essential for writing clear and concise Python code.

Scroll to Top