Python abs() 函式



Python 的abs()函式返回數字的絕對值。簡單來說,數字'x'的絕對值計算為x與0之間的(正)距離。

abs()函式接受所有型別的數字,包括實數和複數,作為引數。絕對值關注的是數字的值或大小,而不是數字附帶的符號。這意味著,如果一個數字是正值,則函式返回相同的值;但如果數字是負值,則返回該數字的相反數。因此,對於需要多步計算大小的複數來說,它更有用。

語法

以下是 Python abs()函式的語法:

abs( x )

引數

  • x − 這是一個數值。

返回值

此函式返回x的絕對值。

示例 1

以下示例演示了 Python abs() 函式的使用。在這裡,讓我們嘗試計算正實數的絕對值。

# Create positive Integer and Float objects
inr = 45
flt = 100.12

# Calculate the absolute values of the objects
abs_int = abs(inr)
abs_flt = abs(flt)

# Print the values
print("Absolute Value of an Integer:", abs_int)
print("Absolute Value of an Float:", abs_flt)

執行以上程式時,將產生以下結果:

Absolute Value of an Integer: 45
Absolute Value of an Float: 100.12

示例 2

正如我們已經討論過的,絕對值只考慮數字的大小。因此,在這個例子中,我們建立了具有負值的數字物件,並將它們作為引數傳遞給 abs() 函式以計算它們的絕對值。

# Create negative Integer and Float objects
inr = -34
flt = -154.32

# Calculate the absolute values of the objects
abs_int = abs(inr)
abs_flt = abs(flt)

# Print the values
print("Absolute Value of an Integer:", abs_int)
print("Absolute Value of an Float:", abs_flt)

讓我們編譯並執行上面的程式,輸出如下所示:

Absolute Value of an Integer: 34
Absolute Value of an Float: 154.32

示例 3

如果我們將複數作為引數傳遞給此函式,返回值將是該複數的大小。

在下面的例子中,我們建立了兩個儲存複數的物件,一個正數,另一個負數。使用abs()函式,計算這些物件的絕對值。

# Create positive and negative complex number objects
pos_cmplx = 12-11j
neg_cmplx = -34-56j

# Calculate the absolute values of the objects created
abs1 = abs(pos_cmplx)
abs2 = abs(neg_cmplx)

# Print the return values
print("Absolute Value of a positive complex number:", abs1)
print("Absolute Value of a negative complex number:", abs2)

編譯並執行上面的程式,得到的輸出如下:

Absolute Value of a positive complex number: 16.278820596099706
Absolute Value of a negative complex number: 65.5133574166368

示例 4

當將 None 值作為引數傳遞給函式時,會引發 TypeError。但是,當我們將零作為引數傳遞時,函式也返回零。

# Create negative Integer and Float objects
zero = 0
null = None

# Calulate and Print the absolute values
print("Absolute Value of Zero:", abs(zero))
print("Absolute Value of a Null:", abs(null))

執行以上程式後,結果顯示如下:

Absolute Value of Zero: 0
Traceback (most recent call last):
  File "main.py", line 7, in 
print("Absolute Value of a Null:", abs(null))
TypeError: bad operand type for abs(): 'NoneType'
python_built_in_functions.htm
廣告