Python complex() function
The complex()
function in Python is used to create a complex number, which is a number that has a real part and an imaginary part. Complex numbers are represented as a + bj
, where a
is the real part and b
is the imaginary part (with j
denoting the imaginary unit).
Syntax
real
(optional): The real part of the complex number. This can be an integer or a float.imag
(optional): The imaginary part of the complex number. This can also be an integer or a float. If omitted, it defaults to0
.
Return Value
- Returns a complex number represented as
a + bj
.
Examples
Creating a complex number with both real and imaginary parts:
Creating a complex number with only the real part: If you provide only one argument, it will be treated as the real part, and the imaginary part defaults to
0
.Creating a complex number with a negative imaginary part: You can also specify negative values for the imaginary part.
Creating a complex number from a string: You can also create a complex number by passing a string representation of a complex number.
Using float values for both parts: You can use floating-point numbers for both the real and imaginary parts.
Using the
real
andimag
attributes: Once you have a complex number, you can access its real and imaginary parts using the.real
and.imag
attributes.Complex conjugate: You can get the complex conjugate of a complex number using the
conjugate()
method.
Summary
- The
complex()
function creates a complex number in Python, represented asa + bj
. - You can specify both the real and imaginary parts, or just the real part.
- It can accept string representations of complex numbers.
- Complex numbers have properties like accessing their real and imaginary parts and obtaining their conjugate.