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:
1 2 |
num = 5+3j print(type(num)) |
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.
1 2 |
num = 5+3j print(isinstance(num, complex)) |
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.
1 2 3 4 5 6 7 8 |
# Direct assignment num1 = 5 + 3j # Using complex() function num2 = complex(5, 3) print(num1) print(num2) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Checking the type num = 5+3j print(type(num)) # Using isinstance() function num = 5+3j print(isinstance(num, complex)) # Creating complex numbers num1 = 5 + 3j num2 = complex(5, 3) print(num1) print(num2) |
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.