Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading