Review: Built-in Functions


#1


I got my code to work, but my original code was:
if type(num) == int or float:
etc...
my question is, why does Python need:
if type(num) == int or type(num) == float:
Just the way the syntax is?


#2

The syntax allows both of them, but if you want to compare float to the type of num, then you'll have to write the code for doing that.

If you treat float as if it were a boolean, then it will be considered truthy:

print bool(float)

True

Some values are falsy, typically those representing lack of value or emptiness. Like an empty list/string, or None


#3

I have this, and cant figure out the error.

I've used all spaces, no tabs

distance_from_zero(distance):
return distance
if type(distance) == int or type(distance) == float:
return abs(distance)
else:
return "Nope"


#4

the forum isn't recognizing my spaces, but there should be 1 space before the if and else and 2 spaces before the returns


#5

Are you defining distance_from_zero(distance):
didn't know if you forgot to include def before that.


#6

i ran out of replies, but the below suggestion worked, thanks!


#7

ok, why do you have return distance after def distance_from_zero(distance):
try removing return distance line and run it.


#8

can someone help me understand why this code works:

def distance_from_zero(N):
if type(N) == int or type(N) == float:
return abs(N)
else:
return "Nope"

and this code does not:

def distance_from_zero(N):
if type(N) == str:
return "Nope"
else:
return abs(N)

The error message I get in this version is: "Your function seems to fail on input True when it returned '1' instead of 'Nope'"


#9

Thanks ionatan! Had the same question!

In case this helps other noobs like me – if I am understanding ionatan correctly – the line

if type(num) == int or float:

is being evaluated as

if (type(num) == int) or (bool(float):

and so

if type(num) == int

is being evaluated correctly

but

or float

is being evaluated as a independent boolean

and since bool(float) is been evaluated as inherently "truthy"

bool(float) will always == True

and so what you're actually writing with

if type(num) == int or float:

is

if type(num) == int or True:

which will always evaluate to True.