Python abs() 函数:绝对值示例

Python abs()

Python abs() 是 Python 标准库中提供的内置函数。它返回给定数字的绝对值。数字的绝对值是没有符号的值。该数字可以是整数、浮点数或复数。如果给定的数字是复数,它将返回其模。

语法

abs(value)

参数 (值)

要获得绝对值,需要将值作为参数传递给 abs()。它可以是整数、浮点数或复数。

返回值

它将返回给定数字的绝对值。

  • 如果输入是整数,则返回值也将是整数。
  • 如果输入是浮点数,则返回值也将是浮点数。
  • 如果输入是复数,则返回值将是输入的模。

示例

代码示例 1:整数和浮点数

要获取整数和浮点数的绝对值,请查看此代码

# testing abs() for an integer and float
  int_num = -25
  float_num = -10.50
  print("The absolute value of an integer number is:", abs(int_num))
  print("The absolute value of a float number is:", abs(float_num))

输出

The absolute value of an integer number is: 25
The absolute value of a float number is: 10.5

示例 2:复数

获取复数的绝对值

# testing abs() for a complex number
complex_num = (3+10j)
print("The magnitude of the complex number is:", abs(complex_num))

输出

The magnitude of the complex number is: 10.44030650891055

摘要

  • Abs() 是 Python 中提供的内置函数,它将返回输入值的绝对值。
  • 值是传递给 abs() 以获取绝对值的输入值。它可以是整数、浮点数或复数。
  • abs() 方法接受一个参数,即您想要获取绝对值的值。
  • abs() 函数返回给定数字的绝对值。