Python complex()

Python complex() builtin function returns a complex number formed by the given real and imaginary parts.

In this tutorial, we will learn about the syntax of Python complex() function, and learn how to use this function with the help of examples.

Syntax

The syntax of complex() function is

</>
Copy
complex([real[, imag]])

where

ParameterRequired/OptionalDescription
realOptionalAny number. This is the real part of the resulting complex number.
imagOptionalAny number. This is the imaginary part of the resulting complex number.

complex() returns 0j.

complex(real) returns real+0j.

complex(str) converts the string into complex number. If string is passed as argument to complex(), then imag part should not be specified.

Returns

The function returns object of type complex.

Examples

1. complex(3, 5)

In this example, we will create a complex number formed by the real number 3 and imaginary number 5.

Python Program

</>
Copy
real = 3
imag = 5
complex1 = complex(real, imag)
print(complex1)

Output

(3+5j)

2. complex() – No arguments

In this example, we will not pass any real number and imaginary number to complex() function.

Python Program

</>
Copy
complex1 = complex()
print(complex1)

Output

0j

3. complex(3) – Only real value

In this example, we will create a complex number formed by the real number 3 and no value for imaginary parameter.

Python Program

</>
Copy
real = 3
complex1 = complex(real)
print(complex1)

Output

(3+0j)

4. complex(‘3+5j’) – Real and Complex parts

In this example, we will give a string to complex() function. The function interprets the given number as complex number.

Python Program

</>
Copy
string = '3+5j'
complex1 = complex(string)
print(complex1)

Output

(3+5j)

Conclusion

In this Python Tutorial, we have learnt the syntax of Python complex() builtin function, and also learned how to use this function, with the help of Python example programs.