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

标签 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 个电机。谢谢。

最佳答案

您需要一个电机列表:

motors = [m1, m2, m3, m4]

所以你可以使用 for 循环:

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

关于python - 使用 For 循环缩短重复代码以递增变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40606920/

相关文章:

python - 在 Python 中迭代一个字符串并添加一些新字符

python - 为 pdf 后端设置 spines 的 capstyle

python - 如何修复这个 "attribute error,:load_multiclass_scores"?

python - 如果我在 Ubuntu 上开始学习 C,它会在我今年夏天晚些时候开始学习 Objective-C 时给我带来优势吗?

python - 附加到具有字典理解的列表字典

python - 使用 dictConfig 时如何重新配置​​记录器格式化程序

python - 向 Django 字段添加附加属性

python - 仅限 Python 创建多项式类

在 Mac 上安装 requests 模块时 Python 2.7 崩溃

python - 使用适用于 Python 2.7 的 MacPorts 安装 Shogun 工具箱