W3Basic Logo

Python abs() Function

The abs() method returns the absolute value of a given number. In addition, if the given number is of a complex type, then the abs() method returns the magnitude of the number.

Example:

# abs in Python
num = -5
print('The Absolute value of -5 is:', abs(num))

Output

The absolute value of -5 is: 5

Syntax

The Syntax of the abs() function is:

abs(number)

Here, number could be an integer, floating-point, complex, etc.

Parameters

The abs() function takes single parameter.

  • number - the number whose absolute value needs to be returned. The number can be of type integer, floating-point or complex.

Return Value

The abs() function returns:

  • For Integers - Returns the absolute integer value
  • For Floating-Point - Returns the absolute floating value
  • For Complex - Returns the magnitude of the number

Example 1: Python Program to get the absolute value of a given number

# Positive Integer number
positive_num = 180
print('An Absolute value of 180 is:', abs(positive_num))

# Negative Integer number
negative_num = -180
print('The Absolute value of -180 is:', abs(negative_num))

# In case of 0
num = 0
print('An Absolute value of 0 is:', abs(num))

# Positive Float number
positive_float_num = 3.14
print('The Absolute value of 3.14 is:', abs(positive_float_num))

# Negative Float number
negative_float_num = -63.34
print('The Absolute value of -63.34 is:', abs(negative_float_num))

Output

An absolute value of 180 is: 180
The absolute value of -180 is: 180
An absolute value of 0 is: 0
The absolute value of 3.14 is: 3.14
The absolute value of -63.34 is: 63.34

Example 2: Python Program to get the magnitude of a complex number

# complex number
complex_num = 5-4j
print('Magnitude of 5-4j is:', abs(complex_num))

# complex number
complex_num = 4-3j
print('Magnitude of 4-3j is:', abs(complex_num))

Output

Magnitude of 5-4j is: 6.4031242374328485
Magnitude of 4-3j is: 5.0

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: