Reputation: 643
Could someone tell how to stop the drawing of this figure in Python?
Modify this code so it stops drawing after a certain number of iterations:
import turtle
g = 134
l = 120
while True:
turtle.speed('fastest')
turtle.left(g)
turtle.forward(l)
Count of iterations should be with input()
when starting the program.
Upvotes: 0
Views: 1371
Reputation: 115
Your code will run forever, since you have created an infinite while
loop. To solve this, you can use a for
loop. The number of iterations can be put in the range()
import turtle
turtle = turtle.Turtle()
g = 134
l = 120
iterations = int(input("..."))
for _ in range(iterations):
turtle.speed('fastest')
turtle.left(g)
turtle.forward(l)
This way, the code will stop running after the specified iterations.
Upvotes: 0
Reputation: 61
Well your problem is that you have your turtle drawing in an infinite loop, you are never really stopping your program from running. when you say:
while True:
turtle.speed('fastest')
turtle.left(g)
turtle.forward(l)
This is your infinite loop and without any set condition for this to stop it never will.Now to answer how you would be able to do this with a set number of iterations. You can do this one of two ways in while
or a for
loop. Most of the time if you want to run a certain block of code a set amount of times a for
loop is your best bet.
import turtle
g = 134
l = 120
num_iter = input()
for i in range(num_iter):
turtle.speed('fastest')
turtle.left(g)
turtle.forward(l)
Here for i in range(num_iter)
this declares a for loop that runs num_iter amount of times. Hopefully this answers your question.
Upvotes: 3