teaching python using turtle module

classic Classic list List threaded Threaded
13 messages Options
Reply | Threaded
Open this post in threaded view
|

teaching python using turtle module

Brian Blais
Hello,

I was just playing with the turtle module, and thought it was an interesting way to augment the introduction to python (I teach college students, who haven't had any programming).  It's a great way to introduce functions, for-loops, and general program structures.

After a bit of playing, I realized that I couldn't think of many examples which use turtle with conditional structures (if- and while- statements), or functions that return values, as opposed to "procedures" like:

def square(length):
    forward(length)
    right(90)
    forward(length)
    right(90)
    forward(length)
    right(90)
    forward(length)
    right(90)


If-statements could possibly be used with some sort of random behavior (if rand()<0.5 ...).  Are there any other situations, using turtle, that these structures would be natural? 



thanks,

Brian Blais



_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Mokurai
On Sun, Nov 29, 2009 at 11:34, Brian Blais <[hidden email]> wrote:
> Hello,
> I was just playing with the turtle module, and thought it was an interesting
> way to augment the introduction to python (I teach college students, who
> haven't had any programming).  It's a great way to introduce functions,
> for-loops, and general program structures.

If you use the Python-programmable tile in Turtle Art in Sugar, or
Smalltalk in the Turtle Graphics in Etoys, it's even better. I have
been doing presentations on teaching Python in elementary schools, and
working on how to teach basic Computer Science ideas. You can use an
if-then-else to initialize a stream in Python for the first pass, and
get a value at each pass thereafter. The logic can be either in the TA
or the Python.

> After a bit of playing, I realized that I couldn't think of many exaples
> which use turtle with conditional structures (if- and while- statements),

Repeat is used much more often. but of course we can provide examples
of any behavior you like. I like to use the turtle to generate
sequences, where I can use a conditional to stop when the turtle would
go off the screen. Fibonacci numbers, for example, or exponentials.
Similarly for spirals of various types. Simple cases like those are
easy to do in TA, while more complex sequences could use Python. There
are several fractal examples using loops provided with Sugar on a
Stick, including variations on Siepinksi constructions, and the Koch
Snowflake.

When I can get the code for reading the color of a dot on the screen
into the programmable tile, I can program a toy Turing machine, with
an array of dots as the transition table, and a line of dots as the
tape.

> or
> functions that return values, as opposed to "procedures" like:
> def square(length):
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)

Surely you mean

repeat(4)
   forward(length)
   right(90)

> If-statements could possibly be used with some sort of random behavior (if
> rand()<0.5 ...).

Drunkard's Walk.

> Are there any other situations, using turtle, that these
> structures would be natural?

Recent versions of TA contain stack instructions: push, pop, read,
clear. Your students might find it interesting to program Forth
instructions in TA or Python. This has practical applications in
implementing and porting virtual machines such as Parrot and the VMs
in Smalltalk and I-APL.

There is plenty more where this came from. You would also be welcome
to adapt the Python source code for TA tiles to your environment.

> thanks,
> Brian Blais
> --
> Brian Blais
> [hidden email]
> http://web.bryant.edu/~bblais
>
>
>
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig
>
>



--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Brian Blais
On Nov 29, 2009, at 17:51 , Edward Cherlin wrote:

If you use the Python-programmable tile in Turtle Art in Sugar, or
Smalltalk in the Turtle Graphics in Etoys, it's even better.

I'll have to check this out.

sequences, where I can use a conditional to stop when the turtle would
go off the screen.

ah, good idea.

or
functions that return values, as opposed to "procedures" like:
def square(length):
    forward(length)
    right(90)
    forward(length)
    right(90)
    forward(length)
    right(90)
    forward(length)
    right(90)

Surely you mean

repeat(4)
   forward(length)
   right(90)


surely I don't mean.  :)

that's not python.  I'd do:

def square(length):
    for i in range(4):
        forward(length)
        right(90)

but there isn't much difference with such a simple shape.  obviously, as one continued, the for-loop method would be clearer.



If-statements could possibly be used with some sort of random behavior (if
rand()<0.5 ...).

Drunkard's Walk.


yes, that was the kind of thing I was thinking about.


thanks!

bb




_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

kirby urner-4
In reply to this post by Mokurai
On Sun, Nov 29, 2009 at 2:51 PM, Edward Cherlin <[hidden email]> wrote:

<< snip >>

> Drunkard's Walk.
>

If our think tank (isepp.org) could have gotten permission, we'd have
used that Monopoly guy (looks kinda like Planters peanut guy) randomly
walking on like some chess board with a lamp post (reminds of Narnia).
 We don't have that kind of dough though, so just do this conceptually
(conceptual art).

>> Are there any other situations, using turtle, that these
>> structures would be natural?
>
> Recent versions of TA contain stack instructions: push, pop, read,
> clear. Your students might find it interesting to program Forth
> instructions in TA or Python. This has practical applications in
> implementing and porting virtual machines such as Parrot and the VMs
> in Smalltalk and I-APL.
>
> There is plenty more where this came from. You would also be welcome
> to adapt the Python source code for TA tiles to your environment.
>

I recall Alan Kay communicating Seymour Papert's sense that having "an
explicit receiver" was an OK development.  What he meant by that, in
Smalltalk terms, is that the original Logo had what I'd call a
"context turtle" in that FORWARD or RIGHT were w/r to a given Turtle
one didn't need to mention explicitly, like what else could one mean?

With Python and other object oriented implementations, one first gives
birth to a turtle, creates an instance, as in:

>>> someturtle = Turtle()

That's binding a name to a turtle object (giving some turtle object a
name) and then controlling said turtle through the API using dot
notation against the name, e.g. someturtle.forward(10) or
someturtle.right(90).

What you get from this is, of course, the possibility of multiple
turtles, each with its own pen color, visibility, other properties of
self-hood.

This gets showcased in the default demo (in Windows, just double click
on turtle.py in the Lib subdirectory):
http://www.flickr.com/photos/17157315@N00/4145780784/
(using Gregor's 3.1 code just minutes ago)

IronPython also has access to the .NET turtle library:
http://www.flickr.com/photos/mfoord/3104991233/
(not my computer)

I suppose I'm only bringing this up to (a) name drop about being in a
meeting with Alan Kay (with Guido and Mark Shuttleworth among others)
and (b) to remind readers that Logo and turtle art, or the art of
programming with turtles, are orthogonal axes.

Logo as a language has also been extended considerably, as has the
richness of the environment.  Some of these are commercial,
proprietary offerings.

Some of these feature "spatial turtles" in a "turtle tank" i.e. each
turtle is more like a biplane in a WWI dogfight (Snoopy vs. Red
Baron), with all those extra degrees of freedom (roll, pitch, yaw).

Python's turtle module is not, repeat not, an implementation of Logo
in the Python language.  It's an implementation of turtle graphics on
a Tk canvas in the Python language.

You'll also find a turtle module in wxPython such as in PythonCard by
Kevin Altis.
http://pythoncard.sourceforge.net/samples/turtle.html

I think Gregor is right to see turtle.py as an easy way to implement
an Objects First approach, consistent with a more generic approach to
math concepts (vectors, polynomials, polyhedra) as objects (types),
extending the OO rubric.

We teach maths as extensible type systems that advance through the
invention of new types, not just as systems evolving through a
progression of proved theorems from fixed axioms.

Kirby


>> thanks,
>> Brian Blais
>> --
>> Brian Blais
>> [hidden email]
>> http://web.bryant.edu/~bblais
>>
>>
>>
>> _______________________________________________
>> Edu-sig mailing list
>> [hidden email]
>> http://mail.python.org/mailman/listinfo/edu-sig
>>
>>
>
>
>
> --
> Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
> Silent Thunder is my name, and Children are my nation.
> The Cosmos is my dwelling place, the Truth my destination.
> http://www.earthtreasury.org/
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig
>



--
>>> from mars import math
http://www.wikieducator.org/Martian_Math
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Gregor Lingl-2
In reply to this post by Brian Blais
Hello Brian,

I think the most natural use of the if statement (using turtle
graphics) occurs in recursive functions drawing trees,
fractals and the like. This is well known from Logo, where
recursion is the canonical way of doing repetitions. (But
note, that Logo has tail recursion optimizaton!)

If you are not yet ready to use recursion with your students,
probably many  of the problems coming to your mind that need
the examination of conditions  can be solved better by using
a conditional loop (i. e. a while -loop in Python) than by
using mere if statements.

That is not the case however, if you have to perform actions in
the body of a loop, that depend on the current situation.
I did a quick search in my repository of examples and found
a fairly short and simple script that demonstrates, what I mean:
a drunken turtle collecting coins (or whatever) on its random walk.


##### Python script using turtle graphics

from turtle import Screen, Turtle
from random import randint

s = Screen()
s.setup(560,560)
s.title("A drunken turtle collecting ...")

s.tracer(False)
writer = Turtle(visible=False)
writer.penup()
writer.goto(0, -275)

coins = []
for i in range(-4,5):
    for j in range(-4, 5):
        if i == j == 0:
            continue
        c = Turtle(shape="circle")
        c.color("", "orange")
        c.shapesize(0.5)
        c.goto(40*i, 40*j)
        coins.append(c)
s.tracer(True)

DRUNKENNESS = 45      
t = Turtle(shape="turtle")
t.color("black","")
points = 0
while abs(t.xcor()) < 200 and abs(t.ycor()) < 200:
    t.forward(5)
    t.right(randint(-DRUNKENNESS, DRUNKENNESS))
    found = None
    for c in coins:
        if t.distance(c) < 10:
            found = c
            break
    if found:
        found.hideturtle()
        coins.remove(found)
        t.shapesize(1+points/5., outline=1+points)
        points += 1

writer.write("{0} points".format(points),
             align="center", font=('Arial', 24, 'bold'))

############## End of script


You can see a screenshot of a run of this script here:

http://www.dropbox.com/gallery/2016850/1/TurtleCollector?h=6b370a

The script could be expanded in several ways, e. g. for
doing statistical investigations or examinig how the
result depends on different parameters like drunkenness etc.
Or you distribute the coins randomly ... Does that alter
the average "harvest"?

Just a suggestion ...

Regards,
Gregor


Brian Blais schrieb:

> Hello,
>
> I was just playing with the turtle module, and thought it was an
> interesting way to augment the introduction to python (I teach college
> students, who haven't had any programming).  It's a great way to
> introduce functions, for-loops, and general program structures.
>
> After a bit of playing, I realized that I couldn't think of many
> examples which use turtle with conditional structures (if- and while-
> statements), or functions that return values, as opposed to
> "procedures" like:
>
> def square(length):
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>
>
> If-statements could possibly be used with some sort of random behavior
> (if rand()<0.5 ...).  Are there any other situations, using turtle,
> that these structures would be natural?
>
>
>
> thanks,
>
> Brian Blais
>
> --
> Brian Blais
> [hidden email] <mailto:[hidden email]>
> http://web.bryant.edu/~bblais <http://web.bryant.edu/%7Ebblais>
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig
>  
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

kirby urner-4
I'm glad turtle graphics intersected my thinking re extended precision
decimals (Decimal type) on edu-sig just now.

I've updated my tmods.py to contain a turtle rendering the plane-net of a T-mod:

http://www.4dsolutions.net/ocn/python/tmod.py (runnable source)
http://www.flickr.com/photos/17157315@N00/4147429781/  (GUI view)

Here's the graphical output:

http://www.flickr.com/photos/17157315@N00/4148139184/in/photostream/
(Python 3.1)

If you actually wanna fold the T, you need to snip off the cap and
reverse it, per this diagram:

http://www.rwgrayprojects.com/synergetics/s09/figs/f86515.html

120 of them, 60 folded left, 60 folded right, all of volume 1/24, make
the volume 5 rhombic triacontahedron.

http://www.rwgrayprojects.com/synergetics/s09/figs/f86419.html

If you blow up the volume by 3/2, to 7.5, the radius becomes phi /
sqrt(2) -- what we're showing with Decimals.

The reason this seems unfamiliar is the unit of volume is the
tetrahedron formed by any four equi-radiused balls in inter-tangency.

I'm spinning this as Martian Math these days, yakking on
math-thinking-l about it, learned it from Bucky Fuller, Dave Koski et
al.

Kirby
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Gregor Lingl-2


kirby urner schrieb:
> I'm glad turtle graphics intersected my thinking re extended precision
> decimals (Decimal type) on edu-sig just now.
>
> I've updated my tmods.py to contain a turtle rendering the plane-net of a T-mod:
>
> http://www.4dsolutions.net/ocn/python/tmod.py (runnable source)
> http://www.flickr.com/photos/17157315@N00/4147429781/  (GUI view)
>  
Nice tiny app! Albeit not an example for using the if statement ;-)
Just to show you how turtle.py enables you to implement this
using quite different approaches to doing geometry, I'd like to add
two more implementations.

Besides you may notice that these do not rely on rather complicated
calculations of distances and angles, using the Pythagorean theorem
and trigonometrics but only on a few more fundamental properties of
the figure.

##### Version 2 - using coordinate geometry without coordinates ;-)
# a different implementation for Kirby's "Plane Net for T-module"

from turtle import *
from math import sqrt

PHI = (sqrt(5)-1)/2

def planeNet(h=500):            
   setup(560,560)
   title("Plane Net for T-module")
   penup()
   back(h/2); left(90); back(h/2); right(90)
   pendown()

   forward(h); left(90)
   forward(h*PHI); A = pos(); forward(h-h*PHI); left(90)
   forward(h*PHI); B = pos(); forward(h-h*PHI); left(90)
   forward(h); C = pos()

   for P in A, B, C:
      goto(P)


##### Version 3 - stamping simple transforms of the shape of
#####  an isosceles rectangular triangle:

from turtle import Screen, Turtle
from math import sqrt

GOLDEN_RATIO = (sqrt(5)-1)/2

def planeNet(h=500.0, phi=GOLDEN_RATIO):            
   s = Screen(); s.setup(560,560); s.title("Plane Net for T-module")
   s.register_shape("recttriangle", ((0, 0), (h, 0), (0, h)))
   designer = Turtle(shape="recttriangle")
   designer.color("black","")
   designer.penup()
   designer.goto(-h/2, h/2)

   for width, height in ((1, 1-phi), (phi, 1-phi), (phi, 1)):
      designer.shapesize(width, height)
      designer.stamp()
      designer.forward(h)
      designer.right(90)
   designer.hideturtle()

Hoping, you will find this a bit interesting,
best regards

Gregor



> Here's the graphical output:
>
> http://www.flickr.com/photos/17157315@N00/4148139184/in/photostream/
> (Python 3.1)
>
> If you actually wanna fold the T, you need to snip off the cap and
> reverse it, per this diagram:
>
> http://www.rwgrayprojects.com/synergetics/s09/figs/f86515.html
>
> 120 of them, 60 folded left, 60 folded right, all of volume 1/24, make
> the volume 5 rhombic triacontahedron.
>
> http://www.rwgrayprojects.com/synergetics/s09/figs/f86419.html
>
> If you blow up the volume by 3/2, to 7.5, the radius becomes phi /
> sqrt(2) -- what we're showing with Decimals.
>
> The reason this seems unfamiliar is the unit of volume is the
> tetrahedron formed by any four equi-radiused balls in inter-tangency.
>
> I'm spinning this as Martian Math these days, yakking on
> math-thinking-l about it, learned it from Bucky Fuller, Dave Koski et
> al.
>
> Kirby
>
>  
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

kirby urner-4
On Mon, Nov 30, 2009 at 4:31 PM, Gregor Lingl <[hidden email]> wrote:

<< fascinating code >>

>
> Hoping, you will find this a bit interesting,
> best regards
>
> Gregor
>

Really enlightening, both mathematically and from a coding point of
view.  I hadn't used turtle.py enough yet to know about the built-in
"context turtle" if you want to just say "forward" and forgo
specifying a target.  That's a nice Logo-ish touch.

Your take on the T is most excellent.

With your permission, I'd be happy to add both versions with
attribution to my online version of tmod.py for the benefit of future
students, and/or I could simply link to this post in the edu-sig
archives (why not both?).

Kirby


--
>>> from mars import math
http://www.wikieducator.org/Digital_Math
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Daniel Ajoy-2
In reply to this post by Brian Blais
An example of using IF in a game with Logo:

http://davidlongman.com/logo/projects/Shoot/docs/pdf/SHOOT.PDF

Daniel


_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Daniel Ajoy-2
In reply to this post by Brian Blais
On Tue, 01 Dec 2009 06:00:01 -0500, <[hidden email]> wrote:

>> After a bit of playing, I realized that I couldn't think of many
>> examples which use turtle with conditional structures (if- and while-
>> statements), or functions that return values

Many of these need the values of trigonometric functions to determine sides or angles.

http://neoparaiso.com/logo/ejercicios-de-geometria.html

take for example construction 24.

(always start at the orange dot)

I imagine you could draw 39, using a single loop and the "mod" function, or is it the "mod" operator in Python...


Of course, construction 22 requires the use of the output of the SQRT function.


About IF:

When drawing star polygons, like 65,66,67,68 it is not intuitive how many sides a polygon is going to have based on the angle of rotation at the tips. You can use IF at the end of every side to check to see IF you are at (0,0) again.

* Solving trig problems with "colorunder":

http://mia.openworldlearning.org/ideas/sby.htm

* Simulation of Train problems:

http://mia.openworldlearning.org/ideas/asw.htm

Daniel

_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

John Posner
In reply to this post by Brian Blais
Hi Brian,

If you want to start a little bit more simply, how about a program that
draws alternating black and white squares. For the students who "get it"
right away, challenge them to expand the program into one that draws an
entire 8x8 checkerboard.

HTH,
John

#------------------------- python 2.6.4
from turtle import *

SIDELEN = 30
COUNT = 8

def DrawBox(count):
    """
    make turtle draw a box at current position,
    using "count" arg to determine fillcolor
    """
    # determine color
    if count % 2 == 1:
        fillcolor('black')
    else:
        fillcolor('white')
   
    # draw box
    begin_fill()
    for i in range(4):
        forward(SIDELEN)
        left(90)
    end_fill()

######## main program

# draw row of boxes
for i in range(COUNT):
    DrawBox(i)
    forward(SIDELEN)

junk = raw_input("Press Enter ...")
#-------------------------

_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

kirby urner-4
In reply to this post by kirby urner-4
Gregor FYI:

You'll find me linking to one Gregor in Vienna in this blog post, just
beneath an archival photo of work by Alexander Graham Bell.[1]

http://worldgame.blogspot.com/2009/12/meeting-with-sam.html

... providing more context and spin for this rhombic triancontahedron
thread, all that much strong thanks to you.

Kirby

[1] Eber, Dorothy Harley. Genius At Work. about AGB is one of my fave
syllabus entries, obscure and fun.

On Mon, Nov 30, 2009 at 4:52 PM, kirby urner <[hidden email]> wrote:

> On Mon, Nov 30, 2009 at 4:31 PM, Gregor Lingl <[hidden email]> wrote:
>
> << fascinating code >>
>
>>
>> Hoping, you will find this a bit interesting,
>> best regards
>>
>> Gregor
>>
>
> Really enlightening, both mathematically and from a coding point of
> view.  I hadn't used turtle.py enough yet to know about the built-in
> "context turtle" if you want to just say "forward" and forgo
> specifying a target.  That's a nice Logo-ish touch.
>
> Your take on the T is most excellent.
>
> With your permission, I'd be happy to add both versions with
> attribution to my online version of tmod.py for the benefit of future
> students, and/or I could simply link to this post in the edu-sig
> archives (why not both?).
>
> Kirby
>
>
> --
>>>> from mars import math
> http://www.wikieducator.org/Digital_Math
>



--
>>> from mars import math
http://www.wikieducator.org/Digital_Math
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: teaching python using turtle module

Daniel Ajoy-2
In reply to this post by Brian Blais
Re: teaching python using turtle module
Posted by: "Pavel Boytchev" elicateam
To: [hidden email]
Tue Dec 1, 2009 9:39 am (PST)


Daniel Ajoy wrote:
> On Tue, 01 Dec 2009 06:00:01 -0500, <[hidden email]> wrote:
>
>>> examples which use turtle with conditional structures (if- and while-
>>> statements)

Here is one with IF and WHILE:

1. draw a box
2. put a turtle inside, set random heading
3. move the turtle forward until it reaches a box's side
4. then the turtle bounces like a ball and continues to move
5. stop after 5 bounces

------------------------
Another one with WHILE:

1. two turtles are on a circle and move along it with different speeds
2. animate the chase until one of the turtle reaches the other

------------------------
Another one with IF:

1. draw the snowflake fractal
2. but when you draw recursively, draw either to the left of the current
segment, or to the right

------------------------
Another one with WHILE and IF:

1. Use a turtle and the Monte-Carlo method to calculate pi with given
precision

------------------------
With IF:

1. draw a Pythagorean tree until branches become smaller than 1 pixel

------------------------

Pavel

_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig