How to ignore non-float value

python

Solution

In Python, it is often easier to ask for forgiveness than permission (EAFP). When you encounter a `ValueError`, `continue` to the next iteration:

try:
    temp_C = float(temp_C)
except ValueError:
    continue # skips to next iteration

Or more compactly (consolidating most of your function):

try:
    temp_C = float(sensor_reading.split(' ')[4].rstrip('C'))
except (ValueError, IndexError):
    continue

Problem

I have a USB temperature logger that uploads to Cosm every 30 seconds. The issue I'm having is that every 5 minutes, when I run the command it reports a text error instead of a number. So I'm trying to figure out a way to get it to either loop until it receives a number or just ignore the text and resume the script (it quits with an error otherwise). My very inelegant solution is to do this: ``` # convert regular error message to number if temp_C == "temporarily": # "temporarily" is used as it happens to be the 4th word in the error message temp_C = 0.0 ``` The current body of code is: ``` while True: # read data from temper usb sensor sensor_reading=commands.getoutput('pcsensor') #extract single temperature reading from the sensor data=sensor_reading.split(' ') #Split the string and define temperature temp_only=str(data[4]) #knocks out celcius reading from line temp=temp_only.rstrip('C') #Removes the character "C" from the string to allow for plotting # calibrate temperature reading temp_C = temp # convert regular error message to number if temp_C == "temporarily": temp_C = 0.0 # convert value to float temp_C = float(temp_C) # check to see if non-float check = isinstance(temp_C, float) #write out 0.0 as a null value if non-float if check == True: temp_C = temp_C else: temp_C = 0.0 ```

Original source