How to Check Complex Numbers in Python

Complex numbers are an essential component in several areas of mathematics and physics. A complex number is a number in the form of a+bj where ‘a’ and ‘b’ are floats and ‘j’ represents the square root of -1. In Python, complex numbers can be defined and manipulated using various built-in methods.

Checking the Type of a Number

To determine whether a number is complex in Python, we use the type() function. If the output of the type() function is <class ‘complex’> then the number is complex.

See the example below:

The Output:

<class 'complex'>

Using isinstance() to Check for a Complex Number

The isinstance() function can be used to check if the given number is complex or not. It returns True if the number is complex; otherwise, it returns False.

The Output:

True

Creating Complex Numbers

There are two ways to create a complex number in Python: either by direct assignment to a variable or by using the built-in complex() function.

The Output:

(5+3j)
(5+3j)

Full Code

In this tutorial, we have learned how to check and create complex numbers in Python. Here is the full code we used:

Conclusion

In this tutorial, you learned how to check complex numbers in Python. You also explored how to create complex numbers using both direct assignment and the built-in complex() function.

With this basic understanding, you can now effectively use and manipulate complex numbers in your Python programs.