Home > Net >  whats the diffrence between t=Turtle(shape="turtle") from code 1 and t.shape("turtle&
whats the diffrence between t=Turtle(shape="turtle") from code 1 and t.shape("turtle&

Time:09-04

Code 1

import random
from turtle import Turtle,Screen
t = Turtle()
screen=Screen()
screen.setup(width=900,height=500)
s=["fastest", "fast", "normal", "slow", "slowest"]
userbet=screen.textinput(title="make your bet",prompt="enter color")
color=["red","yellow","green","purple","orange"]
y=[-70,-40,-10,20,50]
for turtle_num in range(0,5):
    t=Turtle(shape="turtle")
    t.color(color[turtle_num])
    t.penup()
    t.goto(x=-230,y=y[turtle_num])
screen.exitonclick()

output for code 1

Code 2

import random
from turtle import Turtle,Screen
t = Turtle()
screen=Screen()
screen.setup(width=900,height=500)
s=["fastest", "fast", "normal", "slow", "slowest"]
userbet=screen.textinput(title="make your bet",prompt="enter color")
color=["red","yellow","green","purple","orange"]
y=[-70,-40,-10,20,50]
for turtle_num in range(0,6):
    t.shape("turtle")
    t.color(color[turtle_num])
    t.penup()
    t.goto(x=-230,y=y[turtle_num])
screen.exitonclick()

output for code 2

So i wanted to know why is code 2 producing only one turtle whereas code 1 is producing 5 turtle as of my knowledge t=Turtle(shape="turtle") from code 1 and t.shape("turtle") these two lines perform same task mostly i am wrong thats why there is diffrence i would be glad if someone can explain me diffrence.

CodePudding user response:

All is in the "mostly", the difference is huge:

The first code creates a new turtle at each iteration, setting a different color and a different destination goto

for turtle_num in range(0,5):
    t = Turtle(shape="turtle")
    t.goto(x=-230,y=y[turtle_num])

That means you do : turtle1 go there, turtle2 go there, turtle3 go there


The second code keeps moving the one and only one turtle instance, and changing it's color

t = Turtle()
for turtle_num in range(0,6):
    t.goto(x=-230,y=y[turtle_num])

That means : turtle go there, then go there, then go there

  • Related