Without explanation, Chapter 2 presents the following Python program, but here shown with numbers to the left of each line in the program.
1 2 3 4 5 6 7 8 9 10 11
from turtle import * from math import * pensize(10) pencolor("blue") penup() goto(20,0) pendown() for i in range(1,101): newangle = 2*i*pi/100 goto( 20*cos(newangle), 20*sin(newangle) )
from turtle import * asks to bring in extra "turtle"
(drawing) features found in Python's library of software.
from math import * accesses mathematical features
from the standard library, so that
pi, cos, sin will be recognized.
pensize(10) is not recognized in Python, but because the
turtle features were included above,
pensize(10) makes sense here:
it changes the size of the drawing pen to be ten units thick (measured in pixels of the screen).
pencolor("blue") is a turtle command to change the color of the
"ink" that the pen will draw with.
penup() to tell the turtle-drawing software to
temporarily not draw, so that the pen can be moved without leaving any mark.
pendown() prepares for drawing.
Finally, there is pure Python on this line:
for i in range(1,101)
is a Python idiom (a quite frequently seen programming style) which describes
a repetitive behavior going through the numbers 1 through 100.
newangle = 2*i*pi/100 is a variable assignment, a topic not
introduced until the third part of the book. Variable assignment in Python is more
complicated and subtle than it might initially seem, so we delay thorough explanation.
newangle is a variable set to be the product of
which steps through 1-100, and 2 times pi (3.14159...) divided by 100.
The idea is that
newangle will incrementally sweep through
360 degrees -- except that instead of degrees,
we use the more mathematical 2*Pi radians.
The final two lines are actually one "logical" line for the program, which is
a command to move the pen to a specified place: it is a point on a circle of
radius 20, where the x-coordinate is found by the expression
20*cos(newangle) and the y-coordinate given by
goto is part of the turtle
suite of commands, but the newangle and expressions like
20*cos(newangle) are pure Python.
In a sense, the program shown is a mixture of three languages: Python, mathematics, and a specialized turtle language for drawing. This is typical of all modern software: multiple languages, some specific to the job, are combined to get results. Some of these are not formally developed as languages (they may be libraries of software, so-called development kits, and the like), but the idea of mixing from different sources is fundamental. Programs are mashups.