Untitled

Pearson Education Limited
Edinburgh Gate
Harlow
Essex CM20 2JE
England and Associated Companies throughout the world
Visit us on the World Wide Web at: www.pearsoned.co.uk
© Pearson Education Limited 2014
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the
prior written permission of the publisher or a licence permitting restricted copying in the United Kingdom
issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS.
All trademarks used herein are the property of their respective owners. The use of any trademark
in this text does not vest in the author or publisher any trademark ownership rights in such
trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this
book by such owners.
ISBN 10: 1-292-02591-3
ISBN 13: 978-1-292-02591-9
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
Printed in the United States of America
Repetition Structures
As you can see, the list contains five numbers, so the loop will iterate five times. Program 8 uses
the range function with a for loop to display “Hello world” five times.
Program 8
1
2
3
4
5
6
7
8
9
10
(simple_loop4.py)
# This program demonstrates how the range
# function can be used with a for loop.
def main():
# Print a message five times.
for x in range(5):
print('Hello world!')
# Call the main function.
main()
Program Output
Hello
Hello
Hello
Hello
Hello
world
world
world
world
world
If you pass one argument to the range function, as demonstrated in Program 8, that argument is used as the ending limit of the sequence of numbers. If you pass two arguments to
the range function, the first argument is used as the starting value of the sequence and the
second argument is used as the ending limit. Here is an example:
for num in range(1, 5):
print(num)
This code will display the following:
1
2
3
4
By default, the range function produces a sequence of numbers that increase by 1 for each
successive number in the list. If you pass a third argument to the range function, that argument is used as step value. Instead of increasing by 1, each successive number in the
sequence will increase by the step value. Here is an example:
for num in range(1, 10, 2):
print(num)
In this for statement, three arguments are passed to the range function:
• The first argument, 1, is the starting value for the sequence.
• The second argument, 10, is the ending limit of the list. This means that the last number in the sequence will be 9.
173
Repetition Structures
• The third argument, 2, is the step value. This means that 2 will be added to each successive number in the sequence.
This code will display the following:
1
3
5
7
9
Using the Target Variable Inside the Loop
In a for loop, the purpose of the target variable is to reference each item in a sequence of
items as the loop iterates. In many situations it is helpful to use the target variable in a calculation or other task within the body of the loop. For example, suppose you need to write
a program that displays the numbers 1 through 10 and their squares, in a table similar to
the following:
Number
Square
1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
10
100
This can be accomplished by writing a for loop that iterates over the values 1 through 10.
During the first iteration, the target variable will be assigned the value 1, during the second
iteration it will be assigned the value 2, and so forth. Because the target variable will reference the values 1 through 10 during the loop’s execution, you can use it in the calculation
inside the loop. Program 9 shows how this is done.
Program 9
1
2
3
4
174
(squares.py)
# This program uses a loop to display a
# table showing the numbers 1 through 10
# and their squares.
Repetition Structures
5
6
7
8
9
10
11
12
13
14
15
16
17
def main():
# Print the table headings.
print('Number\tSquare')
print('--------------')
# Print the numbers 1 through 10
# and their squares.
for number in range(1, 11):
square = number**2
print(number, '\t', square)
# Call the main function.
main()
Program Output
Number Square
--------------1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
10
100
First, take a closer look at line 7, which displays the table headings:
print('Number\tSquare')
Notice that inside the string literal the \t escape sequence between the words Number and
Square. Recall that the \t escape sequence is like pressing the Tab key; it causes the output
cursor to move over to the next tab position. This causes the spaces that you see between
the words Number and Square in the sample output.
The for loop that begins in line 12 uses the range function to produce a sequence containing the numbers 1 through 10. During the first iteration, number will reference 1, during
the second iteration number will reference 2, and so forth, up to 10. Inside the loop, the
statement in line 13 raises number to the power of 2 (recall that ** is the exponent operator), and assigns the result to the square variable. The statement in line 14 prints the value
referenced by number, tabs over, and then prints the value referenced by square. (Tabbing
over with the \t escape sequence causes the numbers to be aligned in two columns in the
output.)
Figure 6 shows how we might draw a flowchart for this program.
175
Repetition Structures
Figure 6
Flowchart for Program 9
Start
Display Table Headings
Is there another
value in the list?
Yes (True)
Assign the next value in
the list to number.
No (False)
square = number**2
End
Display the number
variable and the
square variable.
In the Spotlight:
Designing a Count-Controlled Loop with the for Statement
Your friend Amanda just inherited a European sports car from her uncle. Amanda lives in
the United States, and she is afraid she will get a speeding ticket because the car’s speedometer indicates kilometers per hour (KPH). She has asked you to write a program that displays
a table of speeds in KPH with their values converted to miles per hour (MPH). The formula
for converting KPH to MPH is:
MPH ⫽ KPH * 0.6214
In the formula, MPH is the speed in miles per hour and KPH is the speed in kilometers per hour.
The table that your program displays should show speeds from 60 KPH through 130 KPH,
in increments of 10, along with their values converted to MPH. The table should look
something like this:
176
Repetition Structures
KPH
MPH
60
37.3
70
43.5
80
49.7
etc. . . .
130
80.8
After thinking about this table of values, you decide that you will write a for loop. The list
of values that the loop will iterate over will be the kilometer-per-hour speeds. In the loop
you will call the range function like this:
range(60, 131, 10)
The first value in the sequence will be 60. Notice that the third argument specifies 10 as the
step value. This means that the numbers in the list will be 60, 70, 80, and so forth. The second argument specifies 131 as the sequence’s ending limit, so the last number in the
sequence will be 130.
Inside the loop you will use the target variable to calculate a speed in miles per hour.
Program 10 shows the program.
Program 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(speed_converter.py)
# This program converts the speeds 60 KPH
# through 130 KPH (in 10 kph increments)
# to MPH.
# Global constants
START = 60
END = 131
INCREMENT = 10
CONVERSION_FACTOR = 0.6214
def main():
# Print the table headings.
print('KPH\tMPH')
print('--------------')
# Print the speeds.
for kph in range(START, END, INCREMENT):
mph = kph * CONVERSION_FACTOR
print(kph, '\t', format(mph, '.1f'))
# Call the main function.
main()
(program output continues)
177