Python complex() function is used to create complex numbers. It’s a built-in function that returns a complex type from the input parameters.
Python complex()
Python complex() function syntax is:
1 2 3 |
class complex([real[, imag]]) |
Some of the important points to remember while using complex() function are:
- Python complex() function returns complex number with value
real + imag*1j
. - We can convert string to complex number using complex() function. If the first argument is string, second argument is not allowed.
- While converting string to complex number, whitespaces in string is not allowed. For example, ‘1+2j’ is fine but ‘1 + 2j’ is not.
- If no argument is passed, then
0j
is returned. - Input arguments can be in any numeric format such as hexadecimal, binary etc.
- Underscores in numeric literals are also allowed from Python 3.6 onwards, refer PEP 515.
Python complex() examples
Let’s look at some complex() function examples.
complex() without any argument
1 2 3 4 5 |
c = complex() print(type(c)) print(c) |
Output:
1 2 3 4 |
<class 'complex'> 0j |
complex() with numeric arguments
1 2 3 4 5 6 7 8 9 10 |
c = complex(1, 1) print(c) c = complex(1.5, -2.1) print(c) c = complex(0xF) # hexadecimal print(c) c = complex(0b1010, -1) # binary print(c) |
Output:
1 2 3 4 5 6 7 |
(1+1j) (1.5-2.1j) (15+0j) (10-1j) <img class="alignnone wp-image-22655 size-full" src="http://all-learning.com/wp-content/uploads/2018/08/Python-complex.png" alt="Python complex()" width="1276" height="736" /> |
complex() with underscore numeric literals
1 2 3 4 |
c = complex(10_000_000.0, -2) print(c) |
Output: (10000000-2j)
complex() with complex number inputs
1 2 3 4 5 6 7 |
c = 1 + 2j c = complex(c, -4) print(c) c = complex(1+2j, 1+2J) print(c) |
Output:
1 2 3 4 |
(1-2j) (-1+3j) |
Notice how complex literals are combined to form a new complex number. If the second argument is a complex number, then the calculation is different.
complex() with string arguments
1 2 3 4 |
c = complex("1+2j") print(c) |
Output: (1+2j)
Let’s see what happens when the input string has white spaces.
1 2 3 |
c = complex("1 + 2j") |
Output: ValueError: complex() arg is a malformed string
Let’s see what happens when the first argument is a string and the second argument is also provided.
1 2 3 |
c = complex("1+j", 2) |
Output: TypeError: complex() can't take second arg if first is a string
What if we try to pass the second argument as String, let’s see what error we get.
1 2 3 |
c = complex(2, "-2j") |
Output: TypeError: complex() second arg can't be a string
That’s all for python complex() function.
Reference: Official Documentation