如何让多个条件同时执行?

时间:2018-01-13 01:18:45

标签: python turtle-graphics

我决定尝试做一个乌龟项目来学习随机命令。我的问题在于此代码:

pos = 360
while a.ycor()<pos:
 a.forward(randint(1,5))
while b.ycor()<pos:
 b.forward(randint(1,5))
while c.ycor()<pos:
 c.forward(randint(1,5))
while d.ycor()<pos:
 d.forward(randint(1,5))
while e.ycor()<pos:
 e.forward(randint(1,5))

如何让所有条件同时执行以开始比赛(所有海龟同时起飞)?

3 个答案:

答案 0 :(得分:1)

我并非100%确定您要尝试做什么,因此假设您希望同时运行多个功能,请使用multiprocessingthreading模块。 快速多处理示例:

import multiprocessing, time

def aFunction(aVar):
    time.sleep(5)
    print(f"Ye {aVar}")

if __name__ == '__main__':
    multiprocessing.freeze_support()

    pool = multiprocessing.Pool(4)
    pool.map(aFunction, [X for X in range(4)])
    input("Press Return to exit")

答案 1 :(得分:0)

您可以尝试使用逻辑运算符AND

pos = 360
while a.ycor()<pos and
      b.ycor()<pos and
      c.ycor()<pos and
      d.ycor()<pos and
      e.ycor()<pos:

     a.forward(randint(1,5))
     b.forward(randint(1,5))
     c.forward(randint(1,5))
     d.forward(randint(1,5))
     e.forward(randint(1,5))

答案 2 :(得分:0)

为避免重复,您可以将变量和方法放在字典中,然后循环遍历它们。

pos = 360

d = {a: a.ycor, b: b.ycor, c: c.ycor, d: d.ycor, e: e.ycor}

for k, v in d.items():
    while v() < pos:
        k.forward(randint(1, 5))