15

Hi this is a piece of code that is supposed to create a function that returns the absolute value of the inputted integer or float. Can't seem to figure out what's wrong with it, here's the code and the error. Any help is appreciated!

here is the code for the function:

import math
def distance_from_zero(num):
    type_entry = type(num)
    if type_entry == int:
        return math.abs(num)
    elif type_entry == float:
        return math.abs(num)
    else:
        return "Not an integer or float!"

here is where I tested out the code by printing the result

print distance_from_zero(4)

here is the error that occurs

Traceback (most recent call last):
  File "python", line 12, in <module>
  File "python", line 5, in distance_from_zero
AttributeError: 'module' object has no attribute 'abs'
Nick T
  • 25,754
  • 12
  • 83
  • 121
  • possible duplicate of [Python basics (functions)](http://stackoverflow.com/questions/16838308/python-basics-functions) – Jon Clements May 31 '13 at 18:07
  • @JonClements same tutorial question; totally different problem – Nick T May 31 '13 at 18:38
  • What gave you the idea that the `math` module had an `abs()` function? It certainly wasn't from reading the [documentation](http://docs.python.org/2/library/functions.html?highlight=abs#abs). – martineau May 31 '13 at 19:32
  • ^^^ Hence the S.O. question... – rGil May 31 '13 at 20:01
  • @martineau probably because starting a tutorial with 'how to read documentation' is a lot less sexy then just writing code that does things, so one tends to guess. – Nick T Jun 02 '13 at 00:07
  • @Nick: Agreed, but when your code doesn't work and you a hint from the error message, spending a few minutes with Python's online documentation to verify an assumption is often gratifying. – martineau Jun 02 '13 at 01:57

5 Answers5

28

abs() is a built-in function, so just replace all occurrences of math.abs with abs.

You should also use the isinstance() function for type checking instead of using type() and comparing, for example:

def distance_from_zero(num):
    if isinstance(num, (int, float)):
        return abs(num)
    else:
        return "Not an integer or float!"

Note that you may also want to include long and complex as valid numeric types.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Whoever is calling `distance_from_zero` is expecting a number so I would raise an exception instead of returning a string. – James Thiele May 31 '13 at 18:48
  • I agree that raising an exception here makes sense, I was just keeping it consistent with the OP's code. If you did want to raise an exception it would make the most sense to just use `abs()` then, or if you really want the new name, `distance_from_zero = abs`. – Andrew Clark May 31 '13 at 19:18
2

As others pointed out, abs is builtin so it isn't imported from the math module.

I wanted to comment on your type checking. Another way that is the most "pythonic" is to use a try: except: block to check the type:

def distance_from_zero(num):
    try:
        return abs(num)
    except ValueError:
        return "Not an numeric type!"

This takes care of the issue that F.J. pointed out, that long and complex won't be considered. This example uses "duck typing" (if it walks like a duck and quacks like a duck, it must be a duck). If abs works, your function succeeds. If you supply something abs doesn't know how to handle a ValueError will be raised an it will return your error message.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
0

just try:

print(str(abs(4)))

Erm i can't make this any shorter.

Here are the availible functions of math: http://docs.python.org/2/library/math.html
And here are the built-ins that you can call directly without imports: http://docs.python.org/2/library/functions.html

Torxed
  • 22,866
  • 14
  • 82
  • 131
  • I assume he's using the same tutorial as [this guy](http://stackoverflow.com/questions/16838308/python-basics-functions) where you are asked to throw an error on certain input. – Nick T May 31 '13 at 18:38
  • @NickT i see, I was on a train and didn't have much time to just give an answer :P – Torxed Jun 01 '13 at 08:56
0

The python math module doesn't have an abs function as this functionality is provided by basic Python. However, looking at the documentation page for python math here you can see that they do in fact have a fabs function. That said, you can change the code to either of the following depending on how much you want to be using the math module versus basic python:

print str(abs(4))

or

import math
print str(math.fabs(4))
Slater Victoroff
  • 21,376
  • 21
  • 85
  • 144
0

And now for something completely different, here is a single expression:

(-num, num)[num > 0] if None < num < '' else "Not a number!"
dansalmo
  • 11,506
  • 5
  • 58
  • 53