0

我创建了一个 for 循环来运行这个 Turtle 图形。我正在尝试创建一个条件,如果用户回答“是”(y)或关闭,则设置为运行海龟程序,或者如果用户回答“否”(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()
4

1 回答 1

0

您正在假设bool()调用"Yes""No"返回布尔值:

answer = bool(question)

它没有。由于两者都是非空字符串,因此它返回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()
于 2020-04-15T20:31:52.273 回答