I have created a for loop to run this Turtle graphic. I am trying to create a condition which is set to run the turtle program if the user answers 'yes' (y) or close, or clear the program if the user answers 'no' (n). I have tried calling the t.clear() and done() functions separately after 'answer = False' but this doesn't seem to work. The program runs anyway, even if the user inputs 'n' and hits enter in the console. Do I need to set up 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()
You're making the assumption that bool()
called on "Yes"
or "No"
returns a boolean value:
answer = bool(question)
It doesn't. Since both are non-empty strings, it returns True
for either. Instead, we can use a boolean expression to get the result you desire, and it requires less code to do so:
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()