What does abs do in Python?

[-12] [5]
Sergio Tapia

[2010-10-19 12:50:08]

[
python
math
]

[ http://stackoverflow.com/questions/3968475]
[DELETED]

I don't understand how the following code works:

```
#CodingBat.com 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(...) 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.

[2] http://en.wikipedia.org/wiki/Absolute_value#Distance

1

[+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**

2

[+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] http://docs.python.org/library/functions.html3

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

What about this:

- 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.

abs(x)

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.

[...]

http://docs.python.org/library/functions.html?highlight=abs#abs

4

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

this will return absolute value of a number: http://www.tutorialspoint.com/python/number_abs.htm

5

Sergio TapiaNik ReimanS.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 ByersPrincipia Mathematicaway? 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