A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-complex-function/ below:

Python complex() Function - GeeksforGeeks

Python complex() Function

Last Updated : 23 Jul, 2025

Python provides a built-in function called complex() to handle complex numbers. A complex number consists of a real part and an imaginary part, represented in the form:

a + bj

Where,

python uses 'j' instead of 'i' (used in mathematics) to represent imaginary numbers.

We can access the real and imaginary parts of the complex numbers using .real and .imag methods respectively.

Example:

Python
# Creating complex numbers
c1 = complex(3, 4)  
c2 = complex(5)     
c3 = complex()      

print(c1)
print(c2)
print(c3)
print(c1.real)
print(c1.imag)

Output
(3+4j)
(5+0j)
0j
3.0
4.0

Let's explore complex() function in detail:

Syntax of complex() function
  1. Without any arguments: complex() returns 0j.
  2. With one argument: complex(x) returns x + 0j.
  3. With two arguments: complex(x, y) returns x + yj.
  4. With a string argument: complex(string) interprets the string as a complex number.
complex() with Int and Float Parameters

When we pass integer or float parameters to the complex() function, it creates a complex number with the given real and imaginary parts.

Example:

Python
c1 = complex(3, 4) 
print(c1)  

c2 = complex(2.5, 3.7)  
print(c2)  
complex() with String inputs

We can also pass a string to the complex() function, provided that the string represents a valid complex number or a real number. The string can be in the form of "a+bj" or simply "a" where a and b are real numbers.

Python
c1 = complex("5.5")  
print(c1)  

c2 = complex("-2")  
print(c2)  

c3 = complex("3+4j")  
print(c3)  

Output
(5.5+0j)
(-2+0j)
(3+4j)

Explanation:

Note: spaces around operators are not allowed and hence, passing such example will throw an error. For example, if we did complex(" 2.3 + 4.5j "), it will throw "ValueError: complex() arg is a malformed string"

Arithmetic of Complex Numbers Python
c1 = complex(4, 3) 
c2 = complex(2, -5) 

print(c1+c2)    # adds c1 and c2
print(c1-c2)    # subtracts c1 and c2
print(c1*c2)    # multiplies c1 and c2
print(c1/c2)    # divides c1 and c2

# Accessing real and imaginary parts
print(c1.real)
print(c1.imag)

Output
(6-2j)
(2+8j)
(23-14j)
(-0.24137931034482757+0.896551724137931j)
4.0
3.0


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4