Python's error messages are pretty good, as these things go: unlike some languages I could mention, they don't feel like random collections of letters. So when Python complains of the comparison
if x > 0:
that
TypeError: no ordering relation is defined for complex numbers
you should take it at its word: you're trying to compare a complex number x
to see whether or not it's greater than zero, and Python doesn't know how to order complex numbers. Is 2j > 0
? Is -2j > 0
? Etc. In the face of ambiguity, refuse the temptation to guess.
Now, in your particular case, you've already branched on whether or not x.imag != 0
, so you know that x.imag == 0
when you're testing x
and you can simply take the real part, IIUC:
>>> x = 3+0j
>>> type(x)
<type 'complex'>
>>> x > 0
Traceback (most recent call last):
File "<ipython-input-9-36cf1355a74b>", line 1, in <module>
x > 0
TypeError: no ordering relation is defined for complex numbers
>>> x.real > 0
True