I am having some issue with an exercise 4.3 #1 in "ThinkPython". The solution given in the book to the exercise doesn't seem to work.
Problem: "Write a function called square that takes a parameter named t, which is a turtle. It should use the turtle to draw a square. Write a function call that passes bob as an argument to square, and then run the program again"
Solution (FROM THE BOOK!)
def square(t):
for i in range(4):
t.fd(100)
t.lt(90)
square(bob)
ERROR:
line 5, in <module>
square(bob)
NameError: name 'bob' is not defined
Why doesn't recognize bob as a parameter of square?
CodePudding user response:
Notice in the description of the problem:
Write a function called square that takes a parameter named t, which is a turtle.
Basically, you'll need to define a
UPDATE:
Responding to the OP's comment, in order to make the function define its own turtle for every call of itself, simply remove the t
from the arguments, and add t = turtle.Turtle()
into the function:
import turtle
def square():
t = turtle.Turtle()
for i in range(4):
t.fd(100)
t.lt(90)
square()
CodePudding user response:
bob
is a variable, which you have not defined. bob
should be a turtle object. In order to instantiate a turtle object, do the following:
import turtle as bob # instantiates turtle object as "bob"
def square(t):
for i in range(4):
t.fd(100)
t.lt(90)
square(bob)
CodePudding user response:
bob
is recognized as a parameter, the only thing is that bob
is supposed to be wrapped around quotation marks, whether it be single quotes or double.
In this scenario, bob
is being passed into the function and look like it is treated as a number, but alphabetic characters will always correspond to strings.
Sorry if this answer is incorrect, I am not very experienced in Turtle Shell Graphics as a whole.