首页 > 解决方案 > 如何在递增值中使用嵌套的 While 循环

问题描述

我对如何在 python 中增加变量感到很困惑,因为不允许使用 ++ 运算符,并且目标是限制龟库 .left 和 .forward 的移动,因为画布的宽度和高度只有 150

while t:
unif = uniform(-75, 75)  # To move face in every possible angle
forw = randint(-1, 1)  # Move every 1 pixel, -1 for back 1 for forward
t.left(unif)
t.forward(forw)
sleep(0.01)
while countt > 75 or countt < -75:
    print("Outside")
    sys.exit(1)
    while unif > 0 or forw > 0:
        countt = + 1
    else:
        break

标签: pythonwhile-loopincrementpython-turtle

解决方案


在 Python 中没有 ++ 运算符的情况下,您可以使用 += 1 来递增 1。请注意,与您的代码不同,= 符号出现在 + 之后。您的代码还有其他问题我们无法解决,因为我们没有完整的代码并且不知道它试图实现什么。下面是增加 while 循环的一般方式。如果将多个 while 循环相互嵌套,则需要在每个循环中递增变量和/或提供条件语句以跳出每个循环。

variable = 0
while variable < 10:
    print("Hi")
    variable += 1

根据要求,这里是多个嵌套循环的示例,包括一个无限循环(While True):

while True:
    n = 0
    while n < 5:
        print(f'n={n} Hi')
        n += 1

        m = 0
        while m < 3:
            print(f'  m={m} You')
            m +=1

            for k in range(2):
                print(f'    k={k} Bye')

    response = input("Should I keep going? Type n to stop: ")
    if response == "n":
        break

推荐阅读