Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is complex() in Python?

Vafa Batool

The complex() function in Python is used to obtain a complex number from a specified real and imaginary number.

Syntax

complex() is declared as shown below:

complex(real, imaginary)

Parameters

  • real: This is a required parameter. real is used to return the real part of the complex number. It can have any of the int, float, or string data types. If the data type of the real number is a string, then the second parameter must be left empty.

  • imaginary: This is an optional parameter. imaginary is used to return the imaginary part of the complex number. If it is not specified, a value of 0 is returned for the imaginary part of the complex number.

Return value

complex() returns a complex number in the form a+bi.

Code

The examples below show the different ways complex() can be used:

This is the simple case, where the real and imaginary numbers are type int:

real = 3
imaginary = 5 
print(complex(real,imaginary))

This example shows the case where only the real number is specified:

real = 5 
print(complex(real))

This example shows a string data type being passed:

Note: You can only pass the real parameter in this case.

real = '10'
print(complex(real))

The final example passes the whole complex number to complex() as a string:

a = '3+2j'
print(complex(a))

RELATED TAGS

python
RELATED COURSES

View all Courses

Keep Exploring