Python中abs
时间: 2025-06-07 08:41:50 浏览: 19
### Python 中 abs 函数的用法与细节
`abs()` 是 Python 内置函数之一,用于返回数字的绝对值。对于整数和浮点数,它返回非负值;对于复数,它返回该复数的模[^4]。
#### 1. 基本语法
`abs(x)` 的参数 `x` 可以是整数、浮点数或复数。以下是不同类型的示例:
```python
# 整数
print(abs(-5)) # 输出: 5
# 浮点数
print(abs(-3.14)) # 输出: 3.14
# 复数
print(abs(3 + 4j)) # 输出: 5.0
```
#### 2. 对于整数和浮点数
当传入的是整数或浮点数时,`abs()` 返回其绝对值,即将负号移除后的正值[^4]。
```python
number = -10
absolute_value = abs(number)
print(f"The absolute value of {number} is {absolute_value}") # 输出: The absolute value of -10 is 10
```
#### 3. 对于复数
当传入的是复数时,`abs()` 计算并返回复数的模。复数 \( a + bi \) 的模为 \( \sqrt{a^2 + b^2} \)[^4]。
```python
complex_number = 3 + 4j
modulus = abs(complex_number)
print(f"The modulus of {complex_number} is {modulus}") # 输出: The modulus of (3+4j) is 5.0
```
#### 4. 实际应用示例
以下是一个使用 `abs()` 的实际场景,例如计算两点之间的距离:
```python
def distance_between_points(x1, y1, x2, y2):
return abs((x2 - x1) + (y2 - y1))
point1_x, point1_y = 0, 0
point2_x, point2_y = 3, 4
distance = distance_between_points(point1_x, point1_y, point2_x, point2_y)
print(f"Distance between points is {distance}") # 输出: Distance between points is 7
```
注意:上述代码中,`abs()` 被用来确保返回的距离为非负值[^4]。
#### 5. 注意事项
- 如果传递给 `abs()` 的参数不是数字类型(如字符串),则会抛出 `TypeError`。
- `abs()` 不支持直接对列表或其他可迭代对象操作,需要先处理其中的元素。
```python
try:
print(abs("string")) # 抛出 TypeError
except TypeError as e:
print(e) # 输出: bad operand type for abs(): 'str'
```
阅读全文
相关推荐

















