Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with function parameter

So I have this assignment to make a turtle draw a polygon using a function: draw_poly(t, n, sz) Where t = turtle name, n = amount of angles and sz = size of each side. I have come up with the following solution:

import turtle

def draw_poly(t, n, sz):
    t = turtle.Turtle()
    angle = 360/n
    for _ in range(n):
        t.forward(sz)
        t.left(angle)

window = turtle.Screen()

draw_poly(tess, 8, 50)

window.mainloop() 

When I run this I get a name error: 'name 'tess' is not defined'. I thought that because in the function tess is in the spot of the paramater t it will use t = turtle.Turtle() in the function but this doesn't appear to work.

like image 722
LST-2020 Avatar asked Mar 15 '26 15:03

LST-2020


2 Answers

You have to create an instance of turtle.Turtle() and to pass the instance to draw_poly. e.g:

import turtle

def draw_poly(t, n, sz):
    angle = 360/n
    for _ in range(n):
        t.forward(sz)
        t.left(angle)

window = turtle.Screen()
tess = turtle.Turtle()
draw_poly(tess, 8, 50)

window.mainloop()
like image 66
Rabbid76 Avatar answered Mar 17 '26 04:03

Rabbid76


As your function currently stands, it doesn't matter at all what you pass as the first argument, because with t = turtle.Turtle() you immediately overwrite whatever has been passed to t. If you want to pass an arbitrary name that you can use within the function, you can do that by passing it as a string (put quotemarks around it). But this should still be distinguished from the turtle instance, for example:

import turtle

def draw_poly(t, n, sz):
    turtle.title('This window is for ' + t + '.')
    t_instance = turtle.Turtle()
    angle = 360/n
    for _ in range(n):
        t_instance.forward(sz)
        t_instance.left(angle)

window = turtle.Screen()

draw_poly('tess', 8, 50)

window.mainloop() 

Or you could let the turtle live outside of the function:

import turtle

def draw_poly(t, n, sz):
    angle = 360/n
    for _ in range(n):
        t.forward(sz)
        t.left(angle)

window = turtle.Screen()

tess = turtle.Turtle()
draw_poly(tess, 8, 50)

window.mainloop() 
like image 35
Arne Avatar answered Mar 17 '26 05:03

Arne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!