Python math module doesn't have abs

Hi, this is the part of the code that should create a function that returns the absolute value of the entered integer or float. I can’t understand what’s wrong with him, here is 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 I checked the code by typing 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' 
+4
source share
5 answers

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

You should also use the isinstance() function to check types instead of using type() and compare, 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 can also include long and complex as valid numeric types .

+17
source

As others have noted, abs is built-in, so it is not imported from the math module.

I wanted to comment on your type of verification. Another way, which is the most "pythonic", is to use the try: except: block to check for type:

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

This concerns the question that F.J. pointed out that long and complex will not be considered. In this example, a duck seal is used (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 does not know how to handle a ValueError , it will be raised and it will return your error message.

+1
source

just try:

 print(str(abs(4))) 

Erm, I can't make it shorter.

Here are the math functions available: http://docs.python.org/2/library/math.html
And here are the built-in modules that you can call directly without importing: http://docs.python.org/2/library/functions.html

0
source

The python math module does not have an abs function, since this functionality is provided by base Python. However, looking at the documentation page for python math here, you can see that they actually have a fabs function. However, you can change the code to any of the following values ​​depending on how much you want to use the math module compared to the base python:

 print str(abs(4)) 

or

 import math print str(math.fabs(4)) 
0
source

And now for something completely different, here is one expression:

 (-num, num)[num > 0] if None < num < '' else "Not a number!" 
0
source

Source: https://habr.com/ru/post/1483845/


All Articles