What is wrong with "if type(a) == int or float:"


#1

def distance_from_zero(a):

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

Oops, try again. Your function seems to fail on input True when it returned '1' instead of 'Nope'


#2

push~~~~~~~push~~~~~~~

if type(a) == int or float:


#3

You have to do,

a = 1
if type(a) in (int, float):
    print(a)

The reason is because the syntax of the comparative == only compares the first thing after it. So you have to use in and pass it a tuple or list of dict or anything that can be iterated over. This will work out for you.


#5

is it ok?
if type(a) == (int, float):


#6

@jackiehello

Nope, that will not work, you are comparing a type of int to a tuple object which will not get you anything.


#7

if type(a) == int or type(a) ==float:

is it ok?


#8

@jackiehello

That will work, but if you need a huge list of comparisons or need to do different things on each then it is not that efficient and can get confusing.

Just stick with

a = 1
if type(a) in (int, float, str):
    print(a)

Doing complex comparisons like this allows us to do things like,

list_of_competitors = [
    int: 'You entered an int type: %s',
    float: 'You entered a float type: %s',
    str: 'You entered a str type: %s'
]

# Pass some data to type check
a = 1
b = 2.01
c = 'Hello'

for item in (a, b, c):
    print(list_of_competitors[type(item)] % item)

Niffy eh?

There are tons of other things that you can do because of this one and it is a huge reason is it allows us to build scalability directly into our code. If you were to hard code your data types into your loop you would have to go back and rewrite that whole section and test for errors/bugs again. Doing it like this we only have one place where we would look for bugs after we get the function working.

EDIT:

I should note on the above for loop in reality you would do

for item in (a, b, c):
    try:
        print(list_of_competitors[type(item)] % item)
    except TypeError:
        print('This is not a valid type: %s' % item)

#9

wow
i love you so much. i love you, you are so good with python:heart_eyes:

and i want to ask, is "==" same with "in"?
e.g.

if type(a) in (int, float, str):
if type(a) == (int, float, str):


#10

@jackiehello

Kinda but not really, the == ask if the next item is equal to the proceeding item. While in ask if the proceeding item(s) are in the following item(s).


#11

i don't understand

is "a" is the proceeding item?
and (int, float, str) is following item?


#12

@jackiehello

It can be anything, it takes the reference of the object and compares it or an object directly.

Example:

a = 32

if a in range(0, 100):
    print(a)

You can also use the is keyword to compare

a = 1
print (1 is a)
# OUTPUT: True

All this is the OOP of python, anything can be referenced anywhere at almost any time, scope is where you can reference things, and all we are using is comparison operators that return True/False statements.