Chapter 6
At both high levels and at the machine level, programs execute statements one after the other. Selection statements allow a program to execute different code depending on what happens as the program runs. This flexibility is another key to the power of computation.
Listing 6.1: Centipede
1 # centipede.py
2
3 from turtle import *
4
5 def centipede(length, step, life):
6 penup()
7 theta = 0
8 dtheta = 1
9 for i in range(life):
10 forward(step)
11 left(theta)
12 theta += dtheta
13 stamp()
14 if i > length:
15 clearstamps(1)
16 if theta > 10 or theta < −10:
17 dtheta = −dtheta
18 if ycor() > 350:
19 left(30)
20
21 def main():
22 setworldcoordinates(−400, −400, 400, 400)
23 centipede(14, 10, 200)
24 exitonclick()
25
26 main()
This program may be harder to read at first than previous examples. It uses what are called “turtle graphics,” explained later in this chapter. Run it, and then you will begin to see what the code is doing. Use “Restart Shell” from the Shell menu in IDLE if your window ever becomes unresponsive.
The new features in this program include the if statement, boolean expressions, and the turtle graphics library. In order to describe if statements, we need to begin with boolean expressions.
Python has an additional data type known as boolean. Variables that hold this type have only two possible values: True or False. Generally, you will use boolean values in expressions rather than variables. Thus, a boolean expression is an expression that evaluates to either True or False. Python has the following comparison operations that return boolean values:
x == y |
Equal. |
x != y |
Not equal. |
x < y |
Less than. |
x > y |
Greater than. |
x <= y |
Less than or equal. |
x >= y |
Greater than or equal. |
⇒ Caution: To test for equality in Python, you must use == rather than =.
⇒ Caution: Avoid using == or != to compare floats; instead, try to use an inequality if you can. The reason is that floating-point calculations are not always exact. See Chapter 9 for an explanation.
Boolean expressions may be combined with these boolean operations:
P and Q |
True if both P and Q are True; otherwise, False. |
P or Q |
True if either P or Q (or both) are True; otherwise, False. |
not P |
True if P is False; otherwise, False. |
The and and or operations short-circuit their evaluation, meaning, for example, that when evaluating P and Q, if P is False, then there is no need to evaluate Q because the result must be False.
Almost all programming languages (including machine languages) have some form of if statement. In Python, the statement has essentially three forms. The simplest is:
if <boolean>:
<body>
In this form, the <boolean> expression is evaluated, and if it is True, then <body> is executed. If the expression is False, then <body> is not executed.
An if statement may contain an optional else clause, which contains alternative code to run when the boolean expression is False:
if <boolean>:
<body1>
else:
<body2>
In this case, <body1> is executed if the boolean expression is True; otherwise, <body2> is executed.
Finally, a sequence of tests may be checked by using the elif option:
if <boolean1>:
<body1>
elif <boolean2>:
<body2>
elif <boolean3>:
<body3>
...
else:
<bodyN>
Here, if <boolean1> is True, then <body1> is executed; otherwise, <boolean2> is evaluated, and if it is True, <body2> is executed; and so on. Later tests are checked only if all preceding tests are False.
Turtle graphics is a type of computer graphics that draws relative to the position of a “turtle” on the screen. The turtle holds a pen, and if the pen is down when the turtle moves, then a line will be drawn. The turtle may also move with the pen up or initiate other types of drawing such as “stamping” its own shape or drawing dots.
Listing 6.1 uses the following functions from the Python turtle module:
penup() |
Stop drawing turtle path. |
forward(x) |
Move forward x. |
left(theta) |
Turn left angle theta (default is degrees). |
stamp() |
Draw turtle shape at current location. |
clearstamps(n) |
Delete first n stamps (if n is positive). |
ycor() |
y coordinate of current location. |
setworldcoordinates(llx, lly, urx, ury) |
Set lower-left and upper-right coordinates. |
exitonclick() |
Close turtle window when clicked. |
You can imagine that the turtle module must provide many other functions in addition to those listed above. You may also have questions about exactly how those functions work. The Python documentation is online, extensive, and provides information like this and much more.
From the “Documentation” link at http://www.python.org, two links will be particularly useful: the Tutorial and the Library Reference.
Tutorial provides informal descriptions of how most things work in Python. Use it when you start to learn a new topic.
Library Reference is a good place to look up specific reference information. For example, at the time of this writing, the complete list of functions in the turtle module is in Section 23.1 of the Library Reference for Python 3.2.
Be sure to use the documentation set that matches your version of Python.
Python provides a star form of the import statement that is helpful when you need to use many names from the same module:
from turtle import *
This imports all names from the module turtle. Use the star sparingly; otherwise, you may find that a module has imported names that you didn’t anticipate.
Occasionally, it is useful to have a function return more than one value:
return <expression1>, <expression2>, ...
The mechanism used to accomplish this will be described later in Chapters 16 and 19.
Hint: an easy way to do this is to put comment symbols at the beginning of those two lines, thereby changing the code into comments. This is called commenting out a section of code.
Do not use the built-in Python function abs(x). Write a main() that tests your function.
You may assume n is not negative. Write a main() that tests your function.
Training Zone | |
---|---|
rate ≥ .90 m |
interval training |
.70 m ≤ rate < .90 m |
threshold training |
.50 m ≤ rate <. 70 m |
aerobic training |
rate < .50 m |
couch potato |
Use the function from Exercise 3.15 to determine m. Write a main() to ask the user for input and display the result.
18.118.24.196