Im trying to write code that checks a list for a value < 0 and if there is one, replace it with 0. Whenever i write my if statement, i get the error in the title, I know its the fact im trying to compare i with 0 but i just cant figure out how to properly get this if statemtnt to work.
import random
cvalues=[]
for i in range(50):
cvalues.append(random.randrange(0,16))
float_cvalues=[float(i) for i in cvalues]
final_cvalues=["{0:.2f}".format(i) for i in float_cvalues]
nvalues=[]
nvalues=[.4*i-.8 for i in float_cvalues]
float_nvalues=[float(i) for i in nvalues]
nvalues_changed=["{0:.2f}".format(i)for i in nvalues]
for i in nvalues_changed:
if(i < 0):
i=0
else:
i=i
test=list(zip(final_cvalues,nvalues_changed))
print(test)
It seems that your code is jumping between str
and float
. If you want to round your numbers to two decimal places, use round()
, don't convert it to string.
Anyways, here's your code, although admittedly, shortened:
import random
float_cvalues = [round(float(random.randrange(0, 16)), 2) for _ in range(50)]
nvalues = [round(float(.4 * i - .8), 2) for i in float_cvalues]
changed_nvalues = [0 if i < 0 else i for i in nvalues]
test = list(zip(float_cvalues, changed_nvalues))
print(test)