I am trying to loop through and count how many times 'Dan' has the color 'green' my sheet looks like this https://i.sstatic.net/zok7b.jpg
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
if str(sheet.cell(row,0).value) == "Dan" and 'green':
i=i+1
else:
pass
print('there are', i)
In this it tells me 2, Which I understand is because python is only looping for Dan and not taking into account my and function. I have tried duplicating my if function using code:
if str(sheet.cell(row,0).value) == "Dan":
if str(sheet.cell(row,0).value) == "green":
i=i+1
else:
pass
print('there are', i)
which python returns 0 I think its related to how I am formatting my call
As Klaus commented, "and" doesn't work like that. In the case of a non empty string, it will always return True.
The example below will return your expected results. I set the "name" and "color" variables to enhance readability.
Note that your second code example would have worked fine, except that you didn't change the column index between the first "if" and the second.
import xlrd
import os
#os.chdir('C:\Users\Dan\Desktop')
cwd = os.getcwd()
excelsheet1 ='Python practice book.xlsx'
book1 = xlrd.open_workbook(excelsheet1)
sheet = book1.sheet_by_index(0)
i=0
for row in range(sheet.nrows):
name = str(sheet.cell(row,0).value)
color = str(sheet.cell(row,2).value)
if name == "Dan" and color == "green":
i=i+1
# There's no need for an "else" statement here.
print('there are', i)