Shailesh Yadav
Shailesh Yadav

Reputation: 301

Complex data type in python

Why can't we enter the imaginary part in complex data type in formats other than decimal number (for example octal/binary/hex)? In real part we can use any form (hexadecimal/octal)

Ex.1:

x = 0B1111 + 20J     #  => valid

Ex. 2:

x = 0B1111 + 0b111J  #  => Syntax Error

Upvotes: 1

Views: 700

Answers (1)

Selcuk
Selcuk

Reputation: 59238

Because in Python, complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range:

https://docs.python.org/3/reference/lexical_analysis.html#imaginary-literals

imagnumber ::=  (floatnumber | digitpart) ("j" | "J")

There is no binary literal support for floats therefore it raises a syntax error.

When you write 0b11+2j, the real part (0b11) is implicitly converted to a float.

Upvotes: 3

Related Questions