Anna Jeanine Anna Jeanine - 23 days ago 6
JSON Question

Python: Checking if a variable is greater or smaller if/else statement

Hi everyone! I am using

Python 2.7
and
xlrd
to convert a
.xlsx
file into a
.json
file! What I want to accomplish too with this script, is to draw conclusions from the input. This will also make sure that less human errors are made. But, there is a problem with my code. The user has to enter a certain value in a cell, which represents pages from a book per hundered. Want I want to check: are there more or less pages than 100. The code which I am using

import sys
import xlrd

dir = '/path/to/JSON/to/write'
dirworksheet = '/path/to/excel/file'

file = sys.argv[1]
fileJSON = sys.argv[1]+'.json'

work_path = os.path.join(dirworksheet,file)
full_path = os.path.join(dir,fileJSON)
worksheet = xlrd.open_workbook(work_path)
sheet_generalinfo = worksheet.sheet_by_index(0)

data_generalinfo = []

for colnumber in range(1, sheet_generalinfo.ncols):
key1 = OrderedDict()
row_value = sheet_generalinfo.col_values(colnumber)
key1['publish_id'] = 1
key1['book_name'] = row_value[1]
key1['pages_per_100'] = float(row_value[2])
if row_value[2]>= 1:
key1['greater_or_smaller']='greater'
else:
key1['greater_or_smaller']='smaller'

key1['samples'] = data_samples

data_generalinfo.append(key1)

json = json.dumps(data_generalinfo)

with open(full_path, 'w') as datafile:
datafile.write(json)

print(full_path)


The code works fine! But when I look at the JSON file, it always says true! I have entered
0.3
in the excel file and
1.4
, but always
greater
is returned. What am I doing wrong in this statement?

Answer

potentially row_value[2] is a string when it's being imported. If so, then it will always be true, because it's comparing a string to a number:

>>> '0.1'>1
9: True

Try converting all to floating points:

key1['pages_per_100'] = float(row_value[2])

Now that you've made things float, it will work, but you need to change your if statement:

for colnumber in range(1, sheet_generalinfo.ncols):
    key1 = OrderedDict()
    row_value = sheet_generalinfo.col_values(colnumber)
    key1['publish_id'] = 1
    key1['book_name'] = row_value[1]
    key1['pages_per_100'] = float(row_value[2])
    if row_value[2]>= 1:
        key1['greater_or_smaller']='greater'
    else:
        key1['greater_or_smaller']='smaller'

You put the float value into key1, but then your if statement still looks at the row_value, which is still a string. Change the line:

if row_value[2]>= 1:

to instead:

if key1['pages_per_100']>= 1: