3

I have a series of checkboxes with simple values (a, b, c, etc.) that when checked, would "trigger" a string of text to appear. The problem is that I will have a great number of checkboxes, and manually repeating my code below for each checkbox is going to be a mess. I am still learning Python and am struggling with creating a loop to make this happen.

Here is my current (working, but undesirable) code:

if a:
 a = 'foo'
if b:
 b = 'bar'
...

My attempt at the loop, which returns box as nothing:

boxes = [a, b, c, ...]
texta = 'foo'
textb = 'bar'
...
for box in boxes:
 if box:
 box = ('text=%s', box)

What should I do to get my loop functioning properly? Thanks!

Óscar López
237k38 gold badges321 silver badges391 bronze badges
asked May 22, 2013 at 22:07

4 Answers 4

4

How about:

mydict = {a:'foo', b:'bar', c:'spam', d:'eggs'}
boxes = [a, b, c]
for box in boxes:
 print('text=%s' % mydict[box])
answered May 22, 2013 at 22:13
Sign up to request clarification or add additional context in comments.

Comments

1

That won't work, you're just assigning to the local variable in the loop, not to the actual position in the list. Try this:

boxes = [a, b, c, ...] # boxes and texts have the same length
texts = ['texta', 'textb', 'textc', ...] # and the elements in both lists match
for i in range(len(boxes)):
 if boxes[i]:
 boxes[i] = texts[i]
answered May 22, 2013 at 22:13

1 Comment

or for box, text in zip(boxes, texts):
1

You should use zip() and enumerate() here:

boxes = [a, b, c, ...]
texts = ['texta', 'textb', 'textc', ...]
for i,(x,y) in enumerate(zip(boxes,texts)):
 if x:
 boxes[i] = y
answered May 22, 2013 at 22:15

Comments

0
a,b,c = (1,0,11)
boxes = {a:'foo', b:'bar', c:'baz'}
for b in ["text=%s" % boxes[b] for b in boxes if b]: 
 print b
answered May 22, 2013 at 22:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.