Search code examples
pythonfunctionvariablesparameter-passingnameerror

Why am I getting a NameError when I pass an argument to a function in python?


Here is my python code:

import turtle

def square(t):
    t = turtle.Turtle()
    for i in range(4):
        t.fd(100)
        t.lt(90)

square(bob)

When I run my code I get the error:

Traceback (most recent call last):
  File "/home/j/python_projects/tp_ex_4.1.py", line 10, in <module>
    square(bob)
NameError: name 'bob' is not defined

I am learning python programming from the book "Think Python How to think like a computer scientist" and I don't understand why my code will not run. I am trying to write a function called square that takes a parameter named t, which is a turtle. I use a for loop to draw a square with the turtle. Then I write a function call that passes bob as an argument to square. Shouldn't bob replace t in my function? Thereby making bob = turtle.Turtle()? What am I missing?


Solution

  • Quite obviously: bob is not defined. It looks like a variable that didn't get any value.

    You might have wanted to write to the last line something like this:

    square('bob')
    

    This way 'bob' is a literal and it will work.