2016-11-15 56 views
1

我画了一个空白,但我认为手动编写此代码似乎过度。我可以使用'for循环'来缩短这个并增加下面的变量吗?使用For循环缩短重复代码以增加变量。

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 

我的预感是沿着此线的东西:

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

这会产生一个错误。对于新手问题抱歉,但我相信必须有一种方法来缩短这个问题。此外,上面的代码将继续包括4个电机。谢谢。

回答

4

你需要电动机的列表:

motors = [m1, m2, m3, m4] 

所以,你可以使用一个for循环:

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

完美。非常感谢,我很欣赏这种回应。 –

+0

欢迎来到美丽的Python世界! –