1

my current solution for a project I'm working on requires that I evaluate the types of the data that are being passed through. However, I'm noticing weird behaviour, the logic of which I can't understand.

one = ["hello",True,14,23.2]

for objects in one:
    if type(objects) is int:
        print(type(objects))

__________________________
Results:
<class 'int'>

The code and results above make sense because there is only one object within the list which is an int. However, when my condition is as shown below, the results look completely illogical to me:

for objects in one:
if type(objects) is int or bool:
    print(type(objects))

________________________
Results:
<class 'str'>
<class 'bool'>
<class 'int'>
<class 'float'>

Why are all types printed? I recognise that the syntax for my if statement might be incorrect, but how would it be incorrect in a way which accepts types 'str' and 'float'? What is the solution?

If this is a duplicate, then apologies. I'm not sure how to phrase this problem to search for!

Edit: This is a duplicate - many thanks for pointing me in the right direction. For those wondering - it breaks down because the code 'or bool' makes Python think I'm asking a separate condition about whether 'bool' is true... it essentially thinks I'm asking this:

if bool:

Rather than this:

if type(objects) is bool:
j panton
  • 232
  • 4
  • 16

0 Answers0