Skip to content
Related Articles

Related Articles

Python complex() Function

Improve Article
Save Article
Like Article
  • Last Updated : 07 Jan, 2022

Python complex() function is a built-in function in python. This method returns a complex number ( real + imaginary) example (5+2j) when real and imaginary parts are passed, or it also converts a string to a complex number.

Syntax:

complex ([real[, imaginary]])  

Parameter:

  • real : numeric type (including complex).It defaults to zero.
  • imaginary : numeric type (including complex) .It defaults to zero.

Return:

  • A complex number in the form of ( real + imaginary) example (5+2j)
  • type : complex

Note: If the first parameter that passed is a string then the second parameter shouldn’t be passed else will raise TypeError. The string must not contain whitespace around + or – operator else it will raise ValueError.

Example 1:

Python3




# numeric type
# nothing is passed
z = complex()
print("Nothing is passed", z)
  
  
# integer type
# passing first parameter only
complex_num1 = complex(5)
print("Int: first parameter only", complex_num1)
  
# passing both parameters
complex_num2 = complex(7, 2)
print("Int: both parameters", complex_num2)
  
# float type
# passing first parameter only
complex_num3 = complex(3.6)
print("Float: first parameter only", complex_num3)
  
# passing both parameters
complex_num4 = complex(3.6, 8.1)
print("Float: both parameters", complex_num4)
print()
  
# type
print(type(complex_num1))


Output

Nothing is passed 0j
Int: first parameter only (5+0j)
Int: both parameters (7+2j)
Float: first parameter only (3.6+0j)
Float: both parameters (3.6+8.1j)

<class 'complex'>

Example 2:

Python3




# string
# only first parameter is to be passed
z1 = complex("7")
print(z1)
  
print()
z2 = complex("2", "3")
  
# This will raise TypeError"
print(z2)


Output:

Example 3:

Python3




# string
# only first parameter is passed
z1 = complex("7+17j")
print(z1)
  
print()
z2 = complex("7 + 17j")
  
# This will raise Valueerror
print(z2)


Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!