简体   繁体   中英

How do I break out of a python while loop in this case?

I don't know how to break out of a python while loop when turtle arrived on t.ycor == 0

import turtle
import msvcrt

turtle.setup(700, 300, 0, 0)
t=turtle.Turtle()
t.up()
t.goto(-300,0)
t.down()
t.write("Start\n(" + str(t.xcor()) + ", " + str(t.ycor()) + ")", False, "center", ("",15))
while True:
        if msvcrt.kbhit():
            c = msvcrt.getch().decode(encoding = 'UTF-8')
        if c == 'j':
            t.left(3)
        elif c == 'k':
            t.right(3)
        elif c == 'g':
            t.forward(5)
            t.right(3)
        while t.ycor() > 0:
            t.forward(10)
            t.right(3)
t.write("End\n(" + str(t.xcor()) + ", " + str(t.ycor()) + ")", False, "center", ("",15))
print("When angle is", str(t.heading()), ", difference of x position is ", str(t.xcor()+300))
input("Press ENTER key to end")

I want to break out of while True: after while t.ycor() > 0: is done, but I don't know how....

Sounds like you are searching for this:

while True:
    if msvcrt.kbhit():
        c = msvcrt.getch().decode(encoding = 'UTF-8')
    if c == 'j':
        t.left(3)
    elif c == 'k':
        t.right(3)
    elif c == 'g':
        t.forward(5)
        t.right(3)
    while t.ycor() > 0:
        t.forward(10)
        t.right(3)
    break

If so, a better solution would be to eleminate the "while True:", because of the break the while loop is only used once - so the while is unnecessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM