如何设置布尔条件以根据用户输入清除或关闭海龟程序?

How do I set a boolean condition to clear or close the turtle program based on user input?

我已经为 运行 这个海龟图形创建了一个 for 循环。我正在尝试创建一个条件,如果用户回答 'yes' (y) 或关闭,则设置为 运行 乌龟程序,或者如果用户回答 'no' (n),则清除程序.我曾尝试在 'answer = False' 之后分别调用 t.clear() 和 done() 函数,但这似乎不起作用。程序 运行 仍然存在,即使用户在控制台中输入 'n' 并按下回车键。我需要设置 return(y, n) 吗?

from turtle import *
import turtle as t

shape('turtle')
speed(15)

# First you need to define a loop function to draw a square
def square():
    for i in range(4):
        t.color('white')
        t.bgcolor('turquoise')
        t.forward(150)
        t.right(90)

# Ask the user for input if they wish to see the Turtle move
question = input("Do you wish to see my animation? y/n: ")
answer = bool(question)
y = True
n = False
if answer == y: 
    answer = True

    for i in range(60):
        square()
        t.right(6)

else: 
    answer = False
    t.clear()

done()

您假设 bool() 调用了 "Yes""No" returns 一个布尔值:

answer = bool(question)

没有。由于两者都是非空字符串,因此它 returns True 都适用。相反,我们可以使用布尔表达式来获得您想要的结果,并且这样做需要更少的代码:

import turtle

# First you need to define a loop function to draw a square
def square():
    for side in range(4):  # unused variable
        turtle.forward(150)
        turtle.right(90)

# Ask the user for input if they wish to see the Turtle move
question = input("Do you wish to see my animation? y/n: ")
answer = question.lower() in ('y', 'yes')

turtle.shape('turtle')
turtle.speed('fastest')

if answer:
    turtle.bgcolor('turquoise')
    turtle.color('white')

    for repetition in range(60):  # unused variable
        square()
        turtle.right(6)

turtle.hideturtle()
turtle.done()