0

I have the following code. Before I added the outer if/else condition, I was getting an error: "'<' not supported between instances of 'NoneType' and 'float'" as the database was returning NoneType occasionally which was being compared to 98.5. To prevent this, I put the outer if condition so that the inner if condition never performs the calculation if the type is NoneType. However, the error still persists. Does anyone know why? Checking in the shell and the error is there too. Is there some way other way of doing this type comparison.

count = 0
get_data = [data for data in cur]

for i in range(len(get_data)):
    if type(get_data[i][2]) != "NoneType":
        if get_data[i][2] < 98.5:
            vsd_stat.append(1)
        else:
            vsd_stat.append(0)
    else:
        count += 1

df = pd.DataFrame(vsd_stat)```

XYZ123
  • 79
  • 7
  • 6
    Because `type` doesn't return a string. Why not just `get_data[i][2] is not None`? – jonrsharpe Feb 01 '22 at 13:15
  • 1
    You could also avoid `i` by iterating over your data directly, something like `for item in get_data:`. Check out [this article](https://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/) for some more info about idiomatically using Python `for` loops. – CrazyChucky Feb 01 '22 at 13:21

1 Answers1

0

A None variable on its own will evaluate to false, otherwise it will be true. See the below example:

i = None
if i:
    print(True)
else:
    print(False)

This outputs False. If you try again with i = 7, it will output True. Therefore, you should be able to replace your if statement with the below in your code for it to work:

if get_data[i][2]:

Edit As pointed out by CrazyChucky, 0 will also evaluate to False, so the below is probably a safer way to do it:

if get_data[i][2] or get_data[i][2] == 0:
Emi OB
  • 2,814
  • 3
  • 13
  • 29
  • 1
    Much simpler than what I came up with eventually... if not isinstance(get_data[i][2], type(None)): – XYZ123 Feb 01 '22 at 13:20
  • @XYZ123 You may still get errors if get_data[i][2] has the possibility to be a string (text) as it won't be able to evaluate if it's greater than 98.5, you may need to add protection for this too. If my answer helped, please accept :) – Emi OB Feb 01 '22 at 13:21
  • 5
    Beware: zero also evaluates to `False`. (So will an empty list, dictionary, or set, not that that would happen in this use case.) – CrazyChucky Feb 01 '22 at 13:23
  • Thanks @CrazyChucky. Didn't think of that. In that case I think my code will work better as 0 is an expected output. – XYZ123 Feb 01 '22 at 13:26
  • `is not None` is still the cleaner and more idiomatic way to check if something is not `None`. – CrazyChucky Feb 01 '22 at 15:41