I have a list which contains the numbers (lijstkleur) 1,4,6,7. I also have a range from 0 till 8. Now i have te following code:
for x in range(0, len(L), 1):
if x in lijstkleur == True:
self.label = Label(self.frame, text=string[x], fg="yellow", bg="red")
self.label.pack(side=LEFT)
else:
self.label = Label(self.frame, text=string[x], fg="white", bg="red")
self.label.pack(side=LEFT)
but all the numbers become white, what is wrong with this if statement
2 Answers 2
No need to use == True
:
if x in lijstkleur:
The expression x in lijstkleur==True
is interpreted as (x in lijstkleur) and (lijstkleur == True)
; a list is never equal to boolean True
and thus you end up testing something and False
, guaranteed to be False
instead. This is called comparison chaining, making expressions like 10 < a < 20
possible.
You can simplify your range()
call to just len(L)
:
for x in range(len(L)):
and there is no need to repeat the .pack()
call:
if x in lijstkleur:
self.label=Label(self.frame,text=string[x],fg="yellow",bg="red")
else:
self.label=Label(self.frame,text=string[x],fg="white",bg="red")
self.label.pack(side=LEFT)
-
And no need for
for x in range(0,len(L),1)
whenfor x in range(len(L))
will do. Orfor x, s in zip(L, string)
. Andself.label.pack(side=LEFT)
can be hoisted ... There's a lot here.hughdbrown– hughdbrown04/03/2013 16:15:07Commented Apr 3, 2013 at 16:15
Your conditional isn't evaluating the way you think it is. It's doing this:
if (x in lijstkleur) and (lijstkleur==True):
The result of lijstkleur==True
is always False
, since a list is never equal to a boolean, so the conditional always returns False
. What you want is this:
if x in lijstkleur:
-
lijstkleur==True
isTrue
.. orFalse
.. neither of them are iterable. Why don't you get any error message?Karoly Horvath– Karoly Horvath04/03/2013 16:15:30Commented Apr 3, 2013 at 16:15 -
@KarolyHorvath Whoops; skipped a piece. Fixed.Henry Keiter– Henry Keiter04/03/2013 16:18:49Commented Apr 3, 2013 at 16:18
-
Ahh.. I forgot that operators can be on both side. Thx!Karoly Horvath– Karoly Horvath04/03/2013 16:45:38Commented Apr 3, 2013 at 16:45