In this tutorial, we will be exploring the
complex() function in Python. This built-in function is used to define complex numbers, which are an extension of the familiar real number system and include a part that’s multiple of ‘i’, where ‘i’ is the square root of -1.
Usage of Complex()
The syntax for using the complex() function is as follows:
This function takes two parameters:
- real: (optional) the real part of complex number. If this parameter is omitted, it defaults to 0.
- imag: (optional) the imaginary part of complex number. If this parameter is omitted, it also defaults to 0.
A Simple Example
To understand how to use this function better, let’s look at a simple example:
# Create a complex number without specifying any parameters print(complex()) # Output: 0j # Create a complex number by specifying only real part print(complex(3)) # Output: (3+0j) # Create a complex number by specifying both real and imaginary parts print(complex(3, 4)) # Output: (3+4j)
Tips and Tricks with Complex()
You can also use variables instead of direct numbers when creating your complex numbers:
real_part = 5 imaginary_part = 6 c = complex(real_part, imaginary_part) print(c) # Output: (5+6j)
complex() function in Python is a powerful tool for dealing with complex numbers. It’s simple to use and can be very handy when you’re working with mathematical computations that involve complex numbers.
In this tutorial, we’ve learned about the
complex() function in Python, its usage, and how to implement it in our code. We hope this guide has been helpful for you. Happy coding!