使用For循环缩短重复代码以增加变量。

时间:2016-11-15 10:00:49

标签: python python-2.7

我正在画一个空白,但我确实认为手动编写这段代码似乎过分了。我可以使用'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个电机。谢谢。

1 个答案:

答案 0 :(得分:4)

您需要一份电机列表:

motors = [m1, m2, m3, m4]

所以你可以使用for循环:

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