-
Notifications
You must be signed in to change notification settings - Fork 0
Python Function Complex
complex()
is a built-in function in Python 3 that hanldles the creation of a complex number according to the arguments passed. It returns a complex number with the value real + imag*1j
when called in form of complex(real, imag)
or converts a string or number to a complex number.
This function takes two types of arguments which are discussed below :
When called with two arguments, both being numbers of any numeric type (including complex), this function returns a complex number using both arguments.
complex(x, y)
function returns a complex number with the value x + y*1j
>>> complex(3, 2)
(3+2j)
>>> complex(3+4j, 6)
(3+10j)
When called with one numeric argument, it returns a complex number using the argument as the real part and an imaginary part of zero.
>>> complex(4)
(4+0j)
If called with no arguments, it returns a complex zero.
>>> complex()
0j
If the first argument is a string, it will be interpreted as a complex number and the function must be called without a second parameter. It will return the interpreted complex number.
>>> complex('3+4j')
(3+4j)
The string must be in the form of a valid complex number, otherwise the function will raise a ValueError
exception and it must not contain whitespace around the central + or - operator. For example, complex('1+2j')
is fine, but complex('1 + 2j')
raises ValueError
.
print(complex(4, 5)) # prints (4+5j)
print(complex(6)) # prints (6+0j)
print(complex()) # prints 0j
print(complex(2.5,5)) # prints (2.5+5j)
print(complex(5,6+8j)) # prints (-3+6j) as 5+(6+8j)*1j = -3+6j
print(complex('10+20j')) # prints (10+20j)
🚀 Run Code
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links