Skip to content

Numeric literals in Python

  • by

In Python, numeric literals are used to represent numerical values directly in the code. There are several types of numeric literals in Python, including integers, floating-point numbers, and complex numbers. Here’s an overview of each type:

Literal TypeExampleDescription
Integer Literal42Decimal notation (base 10)
0b101010Binary notation (base 2)
0o52Octal notation (base 8)
0x2AHexadecimal notation (base 16)
Floating-Point Literal3.14159Decimal floating-point notation
2.5e-3Scientific notation (0.0025)
Complex Literal3 + 4jComplex number (3 + 4i)

Integer literals: Integers are whole numbers without any fractional part. They can be written in decimal, binary, octal, or hexadecimal notation.

Floating-point literals: Floating-point numbers represent real numbers with a fractional part. They are written using the decimal notation with or without an exponent.

Complex number literals: Complex numbers are written as real + imagj, where real is the real part, imag is the imaginary part, and j represents the imaginary unit.

Basic examples:

# Integer literals
a = 42
b = 0b101010
c = 0o52
d = 0x2A

# Floating-point literals
pi = 3.14159
small_value = 2.5e-3

# Complex number literals
z = 3 + 4j

Python automatically determines the type of the numeric literal based on the syntax used. For instance, without any suffix, a whole number is considered an integer, and a number with a decimal point or exponent is treated as a floating-point number. Complex literals are identified by the presence of the j suffix.

Numeric literals in Python example

Let’s see an example that showcases different types of numeric literals in Python:

# Integer literals
decimal_number = 42
binary_number = 0b101010
octal_number = 0o52
hexadecimal_number = 0x2A

# Floating-point literals
pi = 3.14159
small_value = 2.5e-3

# Complex number literals
complex_number = 3 + 4j

# Printing the values
print("Integer literals:")
print("Decimal:", decimal_number)
print("Binary:", binary_number)
print("Octal:", octal_number)
print("Hexadecimal:", hexadecimal_number)

print("\nFloating-point literals:")
print("Pi:", pi)
print("Small value:", small_value)

print("\nComplex number literal:")
print("Complex number:", complex_number)

Output:

Numeric literals in Python

In this example, we have used different numeric literals for various data types. The output shows the values assigned to each variable using the respective numeric literal representation.

Note: The binary, octal, and hexadecimal literals are internally converted to decimal values, as you can see in the output.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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