Python Forum

Full Version: Function for returning absolute numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am just beginning to learn python, this was an exercise I got from a resource online and tried to solve.

The code below is supposed to take an argument, check whether it is an integer or float in which case it should return the absolute value of the number, otherwise it returns a "Nope" string.

When I run the code below, I just get a "Nope" even when i input an integer or a float. I use the atom text editor and run it from windows powershell...


num = raw_input('Enter a number: ')

def distance_from_zero(num):
if type(num) == int or type(num) == float:
print abs(num)
else:
print 'Nope'

distance_from_zero(num)
It run as expected here: Python 3.6. On 2.7 runs also.

sinstance(object, type or type tuple)

In your case isinstance(num, (int, float)) will return what you want

Repost your code in code tags so we can see the proper indentation
raw_input() always returns a string.  So your type checking will always fail, since a string is never an int or a float.