0

Less or equal when using str for input is returning the opposite value. I have the following code to read the sensor, and I would like to return the value 1 or 2, based on actual sensor reading:

#!/usr/bin/python
import smbus
import time
import subprocess

DEVICE     = 0x23 # Default device I2C address

POWER_DOWN = 0x00 # No active state
POWER_ON   = 0x01 # Power on
RESET      = 0x07 # Reset data register value

CONTINUOUS_LOW_RES_MODE = 0x13
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
ONE_TIME_HIGH_RES_MODE_1 = 0x20
ONE_TIME_HIGH_RES_MODE_2 = 0x21
ONE_TIME_LOW_RES_MODE = 0x23

bus = smbus.SMBus(1)  # Rev 2 Pi uses 1

def convertToNumber(data):
  # Simple function to convert 2 bytes of data
  # into a decimal number
  return ((data[1] + (256 * data[0])) / 1.2)

def readLight(addr=DEVICE):
  data = bus.read_i2c_block_data(addr,ONE_TIME_HIGH_RES_MODE_1)
  return convertToNumber(data)

result=str(readLight());
if result<=2:
       result=1
else:
       result=2
print result

str(readLight() returns the value 0.0, meaning the result <=2 and should print 1, but it prints 2. It works correcty by using numbers instead of str(readLight().

This works correctly:

result=1;
    if result<=2:
           result=1
    else:
           result=2
    print result
burek
  • 23
  • 3

3 Answers3

4

You're comparing a string and an int.

When you write:

result=str(readLight());
if result<=2:
       result=1
else:
       result=2
print result

result gets a string value, not an int. You should use result = int(readLight()) instead.

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
2

The type of str(readLight() is a string, not a number type.

Therefore you are comparing "0.0" with 2. In Python 2.x, it's legal, but the result is not what you expected, their type names are compared:

>>> "0.0" < 2
False
>>> 0.0 < 2
True

In Python 3.x, "0.0" < 2 is illegal.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

You are comparing the numbers as string which is not the same as comparing them as integers. The < > == operators are not going to work as you expect.

You should convert the string to integers first and then compare. You can use the int() function to do it. or just remove the str() call.

You can have a look at this question: String comparison

Community
  • 1
  • 1