Stack OverflowWhat does abs do in Python?
[-12] [5] Sergio Tapia
[2010-10-19 12:50:08]
[ python math ]

I don't understand how the following code works: Warmup 7
#Given an int n, return True if it is within 10 of 100 or 200. 

def near_hundred(n):
    return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))

What does "abs()" do? And how does this work to solve the problem above?

[+18] [2010-10-19 12:51:28] Mark Byers [ACCEPTED]

You can find out by typing abs in the interactive prompt:

>>> abs
<built-in function abs>
>>> help(abs)
    abs(number) -> number

    Return the absolute value of the argument.

In other words abs is a built-in function defined such that abs(x) gives the absolute value [1] of x. This means that if x is positive it returns x, otherwise -x. Another way of saying it is that it returns the value of x without the sign.

In your example abs(100 - n) is the difference between n and 100 expressed as a positive number. You can think of it as the distance [2] between n and 100.


Great answer, I'll accept this answer when the 5 minutes are up. Thanks! - Sergio Tapia
Nice answer... teach a man to fish! - Nik Reiman
(2) +1 even though it's a terrible answer. "#Note: abs(num) computes the #absolute value of a number." was in the code. Why do all this "thinking" and "typing" when one could simply read? - S.Lott
(2) @S.Lott: +1 even though it's a terrible answer. Ermm.....?? Why do all this "thinking" and "typing" when one could simply read? - Code comments aren't always accurate. And he might not have known what "absolute value" meant... - Mark Byers
(1) @Mark Byers: And the on-line help will define absolute value in more more Principia Mathematica way? The comments sure seem to be precisely and completely focused on being explanatory. While your answer is a great answer (deserving at least 10 upvotes) it totally misses the hilarious silliness of someone who did not actually read the actual comments and merely posted code with a dumb question. - S.Lott
[+8] [2010-10-19 13:25:39] Jimmy

It says what it does in your code sample...

#Note: abs(num) computes the #absolute value of a number.

(2) +1: Hilarious. Multi-upvotes are deserved. - S.Lott
+1 for pointing out that the answer was in the question. - John
[+4] [2010-10-19 12:51:14] Tim

Inbuilt function abs() [1] returns the absolute value of a number. (The numerical value without regard to its sign)

abs(-1) #Returns 1
abs(1)  #Also returns 1

[+1] [2010-10-19 12:52:54] sleske

What about this:

  1. Built-in Functions

The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.


Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.


[-1] [2010-10-19 12:54:30] Keshan

this will return absolute value of a number: