What is wrong with my IF ELSE statement?
IF NOT condition, do A.
ELSE, do B.
But the result turns out quite different than I expected. :S
data['stock'] = ['0.02', '0.03', '0.04', '0.00', '0.05', '0.04', '0.05']
x = 0
y = len(data['Keywords'])
while x <= y - 1:
if data['stock'][x] != 0:
print data["stock"][x]
a = a + 1
else:
print "hello"
a = a + 1
Output:
0.02
0.03
0.04
0.00
0.05
0.04
0.05
One obvious problem is that your list contains strings and your code expects numbers. In Python, you are allowed to compare
0to"0"(they compare unequal).One way to fix it:
Also, that loop looks decidedly un-Pythonic. The first step would be to rephrase it like so:
If you don’t use the value of
xother than for indexing into the list, then the counter is unnecessary:Note that this assumes that
data["Keywords"]has the same length anddata["stock"]. If that’s not the case, this code isn’t equivalent to yours.