Search code examples
pythonwhile-loopincrementpython-turtle

How to use Nested While Loop in Incrementing values


Im quite confused on how can i can increment a variable in python since ++ operator is not allowed and the objective is to limit the the movement of turtle lib .left and .forward given that the canvas has only a width and height of 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

Solution

  • In absence of the ++ operator in Python, you use += 1 to increment by one. Notice that unlike your code, the = sign comes after +. There are other problems with your code that we can't fix since we don't have the whole code and don't know what it's trying to achieve. Below is the general way a while loop is incremented. If you nest multiple while loops inside each other, you need to increment the variables within each loop and/or provide conditional statements to break out of each loop.

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

    Upon request, here is an example of multiple nested loops, including an infinite loop (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