Chapter 6

Selection: If Statements

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.

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.

If Statements

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.

Python Turtle Module

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.

Using the Python Documentation

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.

Import Star

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.

Multiple Return Values

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.

Exercises

  1. 6.1 Explain the difference between = and == in Python.
  2. 6.2 Evaluate these boolean expressions:
    1. (a) 1.4 ** 2 > 2
    2. (b) 6 // 7 == 1 // 7
    3. (c) 10 >= 11 or 11 < 12
    4. (d) 3 > 1 and 4.25 > 9 / 2
  3. 6.3 Write the mathematical condition “x is in the interval (2, 3]” as a Python boolean expression.
  4. 6.4 Describe the circumstances when the or operation can short-circuit, and briefly explain why that behavior is correct.
  5. 6.5 List all local variables used in Listing 6.1 and describe the scope of each.
  6. 6.6 Determine the range of x and y values for the turtle screen in Listing 6.1. Use print(xcor(), ycor()) to verify your answer.
  7. 6.7 Determine the initial location and orientation of the turtle in a turtle graphics program.
  8. 6.8 Describe the effect of changing each of these quantities in Listing 6.1:
    1. (a) length
    2. (b) step
    3. (c) life
    4. (d) dtheta
    5. (e) The 350 in line 18
    6. (f) The 10 and −10 in line 16
  9. 6.9 Is it possible to turn right using the turtle left() function? Explain why or why not.
  10. 6.10 Use Listing 6.1 to answer these questions:
    1. (a) Describe the effect of removing the if statement (and its body) at line 14. Explain the result.

      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.

    2. (b) Describe the effect of removing the if statement (and its body) at line 16. Explain the result.
    3. (c) Describe the effect of removing the if statement (and its body) at line 18. Explain the result.
  11. 6.11 Modify Listing 6.1 to keep the pen down rather than up. Describe the effect.
  12. 6.12 Modify line 16 of Listing 6.1 to use the built-in absolute value function abs() instead of an or expression.
  13. 6.13 Modify Listing 6.1 to prevent it from escaping across all four sides.
  14. 6.14 Modify Listing 6.1 to produce an interesting different behavior of your choice.
  15. 6.15 Write an interesting turtle graphics program of your choice.
  16. 6.16 Write a function grade(score) that returns the corresponding letter grade for a given numerical score. Use 90 or above for an A, 80 for a B, etc. Write a main() that tests your function.
  17. 6.17 Write a function mymax2(x, y) that returns the larger of x and y. Do not use the built-in Python function max(). Write a main() that tests your function.
  18. 6.18 Write a function mymax3(x, y, z) that returns the largest of x, y, and z. Do not use the built-in Python function max(). Write a main() that tests your function.
  19. 6.19 Write a function median3(x, y, z) that returns the middle value among x, y, and z. (If two of the values happen to be the same, that value is the median.) Do not use any built-in Python sorting functions. Write a main() that tests your function.
  20. 6.20 Write a function sort3(x, y, z) that returns the three values x, y, and z in sorted order (a, b, c), where a ≤ b ≤ c. Do not use any built-in Python sorting functions, but you may put if statements inside of other if statements. Write a main() that thoroughly tests your function.
  21. 6.21 Rewrite the function median3(x, y, z) of Exercise 6.19 using the function sort3() from Exercise 6.20. Use multiple assignment (see page 95) to store the return values of sort3().
  22. 6.22 Write a function myabs(x) that returns | x |, the absolute value of x, which is given by:

    |x|={xif x  0xotherwise

    Do not use the built-in Python function abs(x). Write a main() that tests your function.

  23. 6.23 Rewrite the myfactorial(n) function from Exercise 4.17 to use this recursive definition:

    n!={1if n = 0 or1n*(n1)!otherwise

    You may assume n is not negative. Write a main() that tests your function.

  24. 6.24 Write a function solvequadratic(a, b, c) that returns the solution(s) of the quadratic equation ax2+bx+c=0 . Use the discriminant d=b24ac to determine whether there are 0, 1, or 2 real roots. Python has a built-in complex() function if you want to return complex roots.
  25. 6.25 Write a function zone(age, rate) that returns a description of a person’s training zone based on his or her age and training heart rate, rate. The zone is determined by comparing rate with the person’s maximum heart rate m:

    Training Zone

    rate ≥ .90 m

    interval training

    .70 mrate < .90 m

    threshold training

    .50 mrate <. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.24.196