Python complex() built-in function

From the Python 3 documentation

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. [...] Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like `int()` and `float()`. If both arguments are omitted, returns 0j.

Introduction

The complex() function creates a complex number. It can take a real and an imaginary part as arguments. If only one argument is provided, it’s considered the real part, and the imaginary part is zero.

Examples

# Create a complex number with real and imaginary parts
print(complex(3, 4))  # Output: (3+4j)

# Create a complex number with only a real part
print(complex(5))     # Output: (5+0j)

# Create a complex number from a string
print(complex("2+3j")) # Output: (2+3j)

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.