Home > Back-end >  How to create multiple turtles in a for loop?
How to create multiple turtles in a for loop?

Time:06-22

Let's say I want to create multiple turtles but also let the user decide how many there is. Is there a way to make a code like this? :

n = input()

for i in range(n):
   'turtle'   i = Turtle()

So you would end up with n turtles called 'turtle1', 'turtle2', ... 'turtle n'

CodePudding user response:

You wouldn't be able to assign them to unique variables that way, but you could always just store them in a list:

n = int(input())
turtles = []

for i in range(n):
   turtles.append(Turtle())

Then you could perform actions on specific turtles by calling on them by their index:

turtles[0].forward(100)
turtles[1].left(20)

CodePudding user response:

problems with the code

  • input() returns a string and range() does not take strings.

  • "turtle" i returns a string object which is immutable so you cant do something like "apple" = "banana"

solution

you can use a list to store the turtle objects in and you can use int() to cast the result from input() into a int.

import turtle
turtles = []
n = int(input())# convert input() into a int
for turtle in range(n):
    turtles.append(Turtle())# append a turtle to the list each iteration

you can access each turtle with its index like this

turtles[0]# first turtle
turtles[1]# second turtle

CodePudding user response:

Python comes with the possibility to execute commands given as strings if passed as argument to the exec() function. The following code does though what you asked for:

from turtle import Turtle
n = 5
for i in range(n):
   exec('turtle'   str(i)   ' = Turtle()')

print(turtle4) # gives <turtle.Turtle object at 0x............>

but it would be much better if you don't use it this way in your code and use a list for this purpose.

Check out generating variable names on fly in python for more on this subject.

CodePudding user response:

n = int(input("Enter the value for the turtles: "))

for i in range(n):
   print(f"turtle{i   1}")
  • Related