02 Two
02 Two
working with
Objects in
Python
parrot.speed = 5 parrot.eat()
canary.width = 2 canary.speak()
parrot.speed = 5 parrot.eat()
canary.width = 2 canary.speak()
t1 = Turtle()
t2 = Turtle()
t1.color("orange")
t2.color("purple")
t1.forward(50)
t1.left(90)
t2.left(90)
t2.forward(50)
done()
Setting up your code:
from turtle import * Importing everything from
the Turtle Module
t1 = Turtle()
Creating two Objects
t2 = Turtle()
Final Output
t1.color("orange")
Assigning the a Color
t2.color("purple") Property to each object
done()
Use Turtle with the basics of Python:
from turtle import * You can use your previous knowledge
to expand with turtle, this includes:
t1 = Turtle()
Using For Loops to repeat
t1.color("orange")
Using Conditional Statements
t1.width(5)
Creating Functions
t1.begin_fill()
for i in range(5):
t1.forward(150)
t1.left(144)
t1.end_fill()
done()
Additional Code Examples:
from turtle import * t = Turtle()
ask = input("Enter shape: ")
def star(t,width,size,color): while ask != "done":
t.color(color) if ask == 'star':
t.width(width) width = int(input("Enter width: "))
t.begin_fill() col = input("Enter a color: ")
for i in range(5): size = int(input("Enter a length: "))
t.forward(size) star(t,width,size,col)
t.left(144) elif ask == 'circle':
t.end_fill() radius = int(input("Enter a radius: "))
col = input("Enter a color: ")
def circle(t,radius,color): circle(t,radius,col)
t.color(color) else:
t.begin_fill() print("No shape entered")
t.circle(radius) ask = input("Enter shape: ")
t.end_fill() done()
Additional Code Examples:
from turtle import * t = Turtle()
ask = input("Enter shape: ")
def star(t,width,size,color): while ask != "done":
t.color(color) if ask == 'star':
t.width(width) width = int(input("Enter width: "))
t.begin_fill() col = input("Enter a color: ")
for i in range(5): size = int(input("Enter a length: "))
t.forward(size) star(t,width,size,col)
t.left(144) elif ask == 'circle':
t.end_fill() radius = int(input("Enter a radius: "))
col = input("Enter a color: ")
def circle(t,radius,color): circle(t,radius,col)
t.color(color) else:
t.begin_fill() print("No shape entered")
t.circle(radius) ask = input("Enter shape: ")
t.end_fill() done()
Code Challenges: