0

I already know this question has been answered a million times, and I tried to follow other user examples and got confused, so bear with me.

I have an assignment where I need to have 1 input integer from user, that makes turtle (I named it jamie) move n number of polygon sides and a function that (pulled from rubric):

has 3 parameters: our_turtle draw a single regular polygon. polygon should have num_sides number of sides, sides of equal length side_length, and all angles in a given polygon will be the same.

It keeps coming back with our_turtle as "NameError: name 'our_turtle' is not defined".

code below

def main():
    import turtle
    jamie = turtle.Turtle()
    num_sides = int(input("please input positive integer that is 3 or greater: "))
    draw_polygon(our_turtle, num_sides, side_length)
    

def draw_polygon(our_turtle, num_sides, side_length):
    our_turtle = jamie.begin_poly()
    side_length = (num_sides - 2) * (180 / num_sides)
    for i in range(num_sides):
        jamie.left(side_length)
    return our_turtle

main()

Did the code and got this error:

please input positive integer that is 3 or greater: 3
Traceback (most recent call last):
  File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 35, in <module>
    main()
  File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 12, in main
    draw_polygon(our_turtle, num_sides, side_length)
NameError: name 'our_turtle' is not defined

I tried putting in our_turtle into main() to see what would happen, and then got this error:

Traceback (most recent call last):
  File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 34, in <module>
    main()
  File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 12, in main
    draw_polygon(our_turtle, num_sides, side_length)
UnboundLocalError: local variable 'our_turtle' referenced before assignment

I will say that local/global variables are really confusing to me, mainly because I am confused as to when python 'switches' between the two? So I am not sure how to fix this problem

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
valikazoo
  • 1
  • 3
  • 1
    You created a `Turtle` object, `jamie`, in your main. It seems that's what you should be _passing_ to your `draw_polygon` function. Then in that function, since you _named the parameter_ as `our_turtle`, then you should be using `our_turtle` inside the function. – Gino Mempin Oct 29 '22 at 05:16
  • Python is not "switching" between local and global variables. You need to understand what functions are, how to call them and pass values/objects to them (passing `jamie` in this case), and use them inside the function (`our_turtle` inside the function now referring to `jamie`). See [Basic explanation of python functions](https://stackoverflow.com/questions/32409802/basic-explanation-of-python-functions) – Gino Mempin Oct 29 '22 at 05:24

0 Answers0