2016-11-15 53 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世界! –