89DEVs

# Python complex() function

```The complex() function returns a complex number based on a given string or a given real and imaginary part. It is also possible to declare a complex number without the complex() function by adding j or J after a number.

Create a complex number with complex()

To create a complex number with the complex() function we can use a string or a given real and imaginary part.

```
# create a complex number with complex()
myComplex = complex(2, 5)
print(myComplex)
```

The complex number 2+5j is returned.

(2+5j)

We can check the type of the created number by using type().

```
# check the type of complex
myComplex = complex(2, 5)
print(type(myComplex))
```

The type of the complex variable is returned and we can confirm that a complex number was created.

<class 'complex'>

The complex() function is also useful to convert a string containing a complex number to a complex type.

```
# convert string to complex number
myComplex = complex('2-5j')
print(myComplex)
```

The complex number is returned.

(2-5j)

Create complex number without complex()

To create a complex number in Python without the complex() function it needs to end with j or J.

```
myComplex = 2-5j
print(myComplex)
```

The complex number is returned.

(2-5j)

complex() syntax

The syntax of the complex function() is:

`complex(real, [imaginary])`

complex() arguments

The complex() function takes 1 or 2 arguments:

required: real, the real part of a complex number.
optional: imaginary, the imaginary part of a complex number

If the first argument is a string, the second argument is optional. The string should be in the format [real](+/-)[imaginary]j.

complex() return value

The complex() function returns a complex number of the type complex.

If the passed arguments don't represent a valid complex number, a ValueError exception is raised.

ValueError: complex() arg is a malformed string

```