• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Absolute value of a number in Python

Absolute value of a number in Python

Author: Aditya Raj
Last Updated: August 3, 2021

While working with numbers in python,we need to compare the magnitude of two numbers irrespective of their sign. For example, Magnitude of -10 is greater than magnitude of 1. But when -10 and 1 is compared, 1 is declared as greater number due to its positive sign. To compare the magnitude of the two numbers, first we need to find the absolute value of  the numbers. Then we can compare the absolute values to compare the magnitude of the numbers. In this article, we will implement programs in python to find the absolute value of different numeric data types.

How to calculate the absolute value of a number in Python?

We can calculate the absolute value of any number in python using the abs() function. The abs() function takes a number as its only argument and returns the absolute value of the number.

The input argument can be a floating point number, an integer or a complex number. We can also pass a binary number, an octal number or a hexadecimal number as input to abs() function.

We can understand the working of the abs() function from the examples in the following section.

Examples using abs() function in Python

We can find an absolute value of an integer using the abs() function as follows.

myNum=10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of 10 is 10.
Absolute value of -10 is 10.

We can find the absolute value of a floating point number using the abs() function as follows.

myNum=10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of 10.5 is 10.5.
Absolute value of -10.5 is 10.5.

If we want to find the magnitude of a complex number, we can do it using the abs() function. The abs() function takes a complex number as input and returns the magnitude of the complex number as follows.

myNum=3+5j
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value of (3+5j) is 5.830951894845301.

We can also determine the absolute value of a number in the decimal number system using the abs() function if the number has been represented in a binary, octal or hexadecimal number system as follows.

#hexadecimal number
myNum=0x123
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))
#binary number
myNum=0b1001
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
#octal number
myNum=0o123
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))

Output:

Absolute value 291 is 291.
Absolute value of 9 is 9.
Absolute value of 83 is 83.

Handling errors during calculation of absolute value

Python is a programming language with dynamic typing. It means that the python interpreter determines the data type of a variable at the runtime. Due to this, it is possible that when we pass a variable as input to the abs() function, it may not be having value with the correct data type to produce the correct output. For example, when we pass a string as input argument to the abs() function, The function will raise a TypeError exception as follows.

myNum="PFB"
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 2, in <module>
    absoluteVal=abs(myNum)
TypeError: bad operand type for abs(): 'str'

We know that when any part of a program raises an exception, the program is terminated immediately . This will result in loss of data written to the file or any significant calculation performed in the program.We can avoid this loss by using exception handling using python try except blocks. The abs() function raises an exception whenever we pass a variable with an incorrect type as input argument to the function. We can handle the exception and save necessary data and close the files by in the except block if needed.

Conclusion

In this article, We have studied about using abs() function in python to find absolute values of numbers. We have also studied how to find the absolute value of numbers in binary, octal and hexadecimal number system in decimal number system. Finally, we saw how to handle any exception generated by the abs() function using try except blocks. Stay tuned for more informative articles.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us