Erik Sven Broberg Erik Sven Broberg - 25 days ago 7
Python Question

Shorten repetitive code with a For Loop to increment variables.

I am drawing a blank, but I do think that writing this code manually seems excessive. Can I use a 'for loop' to shorten this and increment the variables below?

pos = 1000

m1.setAsHome() # set position as zero for all of the commands
m1.goTo(pos) # move to the original position oof the limit switch
while(m1.isBusy()):
continue
m1.free() # reset the motor

while(m2.isBusy()):
continue
m2.setAsHome() # set position as zero for all of the commands
m2.goTo(pos) # move to the original position oof the limit switch
while(m2.isBusy()):
continue
m2.free() # reset the motor


My hunch is something along the lines of this:

for i in range(4):
m = 0
print m[i].setAsHome()


of course this yields an error. Sorry for the newbie question, but I am sure there must be a way to shorten this. Furthermore, the code above keeps going to include 4 motors. Thank you.

Answer

You need a list of motors:

motors = [m1, m2, m3, m4]

So you can use a for loop:

for motor in motors:
    motor.setAsHome()
    motor.goTo(pos)