Python complex()函数
Python complex()函数是Python中的内置函数。当传递实部和虚部时,此方法返回一个复数(实数 + 虚数)示例 (5+2j),或者它还将字符串转换为复数。
句法:
complex ([real[, imaginary]])
范围:
- real :数字类型(包括复数)。默认为零。
- imaginary :数字类型(包括复数)。默认为零。
返回:
- (实数+虚数)形式的复数示例 (5+2j)
- 类型:复杂
注意:如果传递的第一个参数是字符串,则不应传递第二个参数,否则将引发 TypeError。字符串不能在 + 或 –运算符符周围包含空格,否则会引发 ValueError。
示例 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))
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)
Python3
# string
# only first parameter is passed
z1 = complex("7+17j")
print(z1)
print()
z2 = complex("7 + 17j")
# This will raise Valueerror
print(z2)
输出
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)
示例 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)
输出:
示例 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)
输出: