2

First, today is the first time I have used Python. I used Perl 15 years ago, so very rusty but eager to learn. I'm trying to convert the following lines into a for loop, using x to increment ONrelay (so ONrelay0, ONrelay1, ONrelay3, and so on):

cpi6x.setbit(board1, cpi6x.ONrelay0)
time.sleep(.300)
cpi6x.setbit(board1, cpi6x.ONrelay1)
time.sleep(.300)
cpi6x.setbit(board1, cpi6x.ONrelay2)
time.sleep(.300)
cpi6x.setbit(board1, cpi6x.ONrelay3)
time.sleep(.300)
cpi6x.setbit(board1, cpi6x.ONrelay4)

I have tried the following, but not surprisingly it doesn't work.

for x in range(0, 5):
    cpi6x.setbit(board1, cpi6x.ONrelay%d) % (x)
    time.sleep(.300)

Any help would be much appreciated!

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
Khaleesi
  • 33
  • 6

2 Answers2

5

That won't work as ONrelay is not a string, but instance attributes, use getattr instead:

for i in range(5):
    obj = getattr(cpi6x, 'ONrelay{}'.format(i))
    cpi6x.setbit(board1, obj)
    time.sleep(.300)
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
0

It would be easier and more Pythonic to put the relays in an array:

relays = [cpi6x.ONrelay0,
          cpi6x.ONrelay1,
          cpi6x.ONrelay2,
          cpi6x.ONrelay3,
          cpi6x.ONrelay4]

for relay in relays:
    cpi6x.setbit(board1, relay)
    time.sleep(.300)

You could also access the individual relays as relays[x] instead of separate variable names.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251