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

Python 绝对()

Python 绝对() 是 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 的一个内置函数,它将返回给定输入的绝对值。
  • Value 是要提供给 abs() 以获取绝对值的输入值。它可以是整数、浮点数或复数。
  • abs() 方法接受一个参数,即您想要获取的绝对值。
  • abs 函数返回给定数字的绝对值。