The Python complex function is utilized to transform integers or strings into complex numbers. This function accepts two optional arguments and produces a complex number as its output. The initial argument is referred to as the real part, while the second is designated as the imaginary part.
Python complex Function Syntax
It has the following syntax:
complex ([real[, imaginary]])
Parameters
- real : It is an optional numeric parameter.
- imaginary : It is an optional numeric parameter.
Return
It returns a complex number.
Different Examples for Python Complex Function
Let’s explore a few instances of the complex function to gain a clearer understanding of its capabilities.
Python complex Function Example 1
This straightforward illustration demonstrates how to utilize the complex function. In this instance, we are providing all the arguments as integers.
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)
Output:
(1+0j)
(1+2j)
Python complex Function Example 2
In this instance, we are supplying values of the float data type, and the result produced by the function is likewise of the float data type.
# Python complex() function example
# Calling function
a = complex(1.5) # Passing single parameter
b = complex(1.5,2.2) # Passing both parameters
# Displaying result
print(a)
print(b)
Output:
(1.5+0j)
(1.5+2.2j)
Python complex Function Example 3
It is also capable of accepting string parameters; however, it is expected to be an integer value.
# Python complex() function example
# Calling function
a = complex('1') # Passing single parameter
b = complex('1.5')
# Displaying result
print(a)
print(b)
Output:
(1+0j)
(1.5+0j)
Python complex Function Example 4
It permits only a single string argument. In the event that the initial parameter is of the string type, it does not allow for the inclusion of a second argument. An error will be produced if an attempt is made to provide a second parameter.
# Python complex() function example
# Calling function
a = complex('1','2') # Passing two parameter
# Displaying result
print(a)
Output:
TypeError: complex() can't take the second arg if first is a string
Python complex Function Example 5
Additionally, it permits the inclusion of a complex number as an argument. Refer to the example provided below.
# Python complex() function example
# Calling function
a = complex(1+2j) # Passing single parameter
b = complex(1+2j,2+3j) # Passing both parameters
# Displaying result
print(a)
print(b)
Output:
(1+2j)
(-2+4j)