Don't understand why code works and why other code doesn't (Built in Function)


#1



https://www.codecademy.com/en/courses/python-beginner-c7VZg/4/3?curriculum_id=4f89dab3d788890003000096#


The first code does not work
The second code does work


What is causing the code to work or not work?


Replace this line with your code. 
def distance_from_zero(n):
    if type(n) == int or float:
        return abs(n)
    else:
        return "Nope"

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


#2

the second one works because you check if the type is float while you just use float in the first one without actually checking if the type is float. If that makes sense.


#3

this condition:

if type(n) == int or float:

has two parts:

type(n) == int

and:

float

float isn't compared to anything, so it will just see if float is true:

if float: 
     print True
else:
     print False

as we can see from this code, float is considered true by python, so the first code, the condition is always true, because float isn't compared with anything


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.