In this tutorial, we are going to learn all about the Python complex() function. complex function in Python is used to return the complex number with a real and imaginary number (real + imaginary) for example 10 + 5j.
In the previous python tutorial, we have seen all about the Python chr() function along with examples.
Headings of Contents
Python complex() function
Python complex function is a Python built-in function that is used to return the complex number by specifying the real and imaginary number. For example 20 + 10j, Here 20 is representing the real number and 10j is representing the imaginary number.
The syntax of complex() function in Python is:-
The complex method in Python accepts two parameters:-
- real:- Required, A number that represents the real part of the complex number.
- imaginary:- Optional, A number representing the imaginary part of the complex number.
The return value of the complex method in Python is a complex number with real and imaginary parts.
Python complex function example
Here we will take some examples to understand Python’s complex() function.
In this example section, I am about to use complex() without any parameter, Let’s see what happens;
The Output will be:- 0j
Using complex() function with a single parameter.
result = complex(12) print(result)
The output will be:- (12+0j)
Using complex() function with the first and second parameters.
result = complex(23, 30) print(result)
The output will be:- (23+30j), Here 23 is the real number and 30j is the imaginary part.
The complex() function is also capable of converting string complex form to the original complex number.
x = '30+50j' result = complex(x) print(result)
The output will be:- (30+50j)
In this example, I am about to use a complex() function with a floating point number. Let’s see.
real = 10.30 imaginary = 12.2 result = complex(real=real, imag=imaginary) print(result)
The Output will be:- (10.3+12.2j)
Creating complex numbers by passing real and imaginary numbers in string numeric form.
real = '10' imaginary = '12' result = complex(real, imaginary) print(result)
Traceback (most recent call last): File "D:\Python Code\test.py", line 85, in <module> result = complex(real, imaginary) TypeError: complex() can't take second arg if first is a string
We will be getting if we will try to pass real and imaginary values in the complex() function as a string because it does not accept.
In this tutorial, you have learned all about the Python complex function that is a part of Python’s built-in functions. This is the best function to create complex numbers as well as convert strings to complex numbers.
If this article helped you, please keep visiting for further python built-in functions tutorials.
Other Python built-in functions
- Python abs() function
- Python all() function
- Python any() function
- Python bin() function
- Python bool() function
- Python callable() function
- Python chr() function
For more information:- Click Here