Python complex() 函數用於將數字或字符串轉換為複數。此方法采用兩個可選參數並返回一個複數。第一個參數稱為實部,第二個參數稱為虛部。
簽名
complex ([real[, imaginary]])
參數
real:它是一個可選的數字參數。
imaginary:它是一個可選的數字參數。
返回
它返回一個複數。
讓我們看一些 complex() 函數的例子來理解它的函數。
Python complex() 函數示例 1
這是一個簡單的例子,展示了 complex() 函數的用法。在這裏,我們傳遞所有整數類型的參數。
# 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)
輸出:
(1+0j) (1+2j)
Python complex() 函數示例2
這裏,我們傳遞的是 float 類型的值,函數生成的輸出也是 float 類型的。
# 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)
輸出:
(1.5+0j) (1.5+2.2j)
Python complex() 函數示例3
它還允許字符串參數,但應該是整數值。
# Python complex() function example
# Calling function
a = complex('1') # Passing single parameter
b = complex('1.5')
# Displaying result
print(a)
print(b)
輸出:
(1+0j) (1.5+0j)
Python complex() 函數示例 4
它隻允許一個字符串參數。如果第一個參數是字符串類型,則不允許傳遞第二個參數。如果我們傳遞第二個參數,它會產生錯誤。
# Python complex() function example
# Calling function
a = complex('1','2') # Passing two parameter
# Displaying result
print(a)
輸出:
TypeError:complex() can't take the second arg if first is a string
Python complex() 函數示例 5
它還允許將複數作為參數傳遞。請參閱下麵的示例。
# 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)
輸出:
(1+2j) (-2+4j)
相關用法
- Python complex()用法及代碼示例
- Python compile()用法及代碼示例
- Python PIL composite()用法及代碼示例
- Python codecs.encode()用法及代碼示例
- Python string count()用法及代碼示例
- Python code.compile_command()用法及代碼示例
- Python Wand color_matrix()用法及代碼示例
- Python math copysign()用法及代碼示例
- Python codeop.compile_command用法及代碼示例
- Python PIL copy()用法及代碼示例
- Python codecs.decode()用法及代碼示例
- Python calendar firstweekday()用法及代碼示例
- Python cmath.isclose()用法及代碼示例
- Python cmp()用法及代碼示例
- Python calendar weekday()用法及代碼示例
- Python callable()用法及代碼示例
- Python cmath.log10()用法及代碼示例
- Python cmath.asinh()用法及代碼示例
- Python OpenCV cv2.rectangle()用法及代碼示例
- Python Wand charcoal()用法及代碼示例
注:本文由純淨天空篩選整理自 Python complex() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。