horstmann c. - python for everyone - 2016.pdf

(24380 KB) Pobierz
Python
for
Everyone
2/e
Cay Horstmann
Rance Necaise
Variable and Constant De nitions
Selected Operators and Their Precedence
(See Appendix A for the complete list.)
[]
**
* / // %
Name
cansPerPack = 6
Initial value
Use uppercase for constants
Sequence element access
Raising to a power
CAN_VOLUME = 0.335
Mathematical Functions
abs(x)
round(x)
max(x1, x2, ...)
min(x1, x2, ...)
Multiplication, division, oor
division, remainder
+ -
Addition, subtraction
< <= > >= != in
Comparisons and membership
not
or
and
Absolute value |x|
Rounds to nearest integer
Largest of the arguments
Smallest of the arguments
Boolean operators
From
math
module:
Square root
x
Truncates to an integer
Sine, cosine, tangent of
x
degrees(x), radians(x)
Converts to degrees or radians
log(x)
,
log(x, base)
Natural log, log
base
(x)
sqrt(x)
trunc(x)
sin(x)
,
cos(x)
,
tan(x)
Strings
s = "Hello"
len(s)
s[1]
s + "!"
s * 2
s.upper()
s.replace("e", "3")
Imports
Module
Imported items
The length of the string:
5
The character with index 1:
"e"
Concatenation:
Hello!
Replication:
"HelloHello"
Yields
"HELLO"
Yields
"H3llo"
from math import sqrt, log
Lists
Conditional Statement
An empty list
friends = []
values = [16, 3, 2, 13]
Executed when condition is true
Second condition (optional)
Executed when
all conditions are
false (optional)
for i in range(len(values)) :
values[i] = i * i
friends.append("Bob")
friends.insert(0, "Amy")
if "Amy" in friends :
n = friends.index("Amy")
friends.pop(n)
Removes nth
else :
Removes last
friends.pop()
friends.remove("Bob")
guests = friends + ["Lee", "Zoe"]
Replication
scores = [0] * 12
Slice
bestFriends = friends[0 : 3]
Condition
if floor >= 13 :
actualFloor = floor - 1
elif floor >= 0 :
actualFloor = floor
else :
print("Floor negative")
Loop Statements
Condition
while balance < TARGET :
year = year + 1
balance = balance * (1 + rate / 100)
Concatenation
Executed while
condition is true
Included
total = sum(values)
largest = max(values)
values.sort()
A container (list, str, range, dict, set)
for value in values :
sum = sum + value
Excluded
List must contain numbers
Use
min
to get the smallest
Function De nition
Tables
table = [[16, 3, 2, 13],
[5, 10, 11, 8],
[9, 6, 7, 12],
[4, 15, 14, 1]]
Function name Parameter name
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
Number of rows
Number of columns
Exits method and
returns result
for row in range(len(table)) :
for column in range(len(table[row])) :
sum = sum + table[row][column]
San Jose State University
Randolph-Macon College
Cay Horstmann
Rance Necaise
Python
for
Everyone
2/e
VICE PRESIDENT AND EXECUTIVE PUBLISHER
DIRECTOR
EXECUTIVE EDITOR
EDITORIAL PROGRAM ASSISTANT
MARKETING MANAGER
SENIOR PRODUCT DESIGNER
ASSOCIATE PRODUCT DESIGNER
DESIGN DIRECTOR
SENIOR DESIGNER
SENIOR PHOTO EDITOR
SENIOR CONTENT MANAGER
SENIOR PRODUCTION EDITOR
PRODUCTION MANAGEMENT SERVICES
COVER DESIGN
COVER PHOTOS
Laurie Rosatone
Don Fowley
Bryan Gambrel
Jessy Moor
Dan Sayre
Jenny Welter
Wendy Ashenberg
Harry Nolan
Madelyn Lesure
Billy Ray
Valerie Zaborski
Tim Lindner
Cindy Johnson
Madelyn Lesure / Wendy Lai
(castle) © Anik Messier/Getty Images;
(cow) © Eric Isselée/Shutterstock;
(parrot) © Eric Isselée/iStockphoto;
(trumpets) © modella/123RF.com.
This book was set in 10.5/12 Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad
Graphics/Versailles. The cover was printed by Quad Graphics/Versailles.
This book is printed on acid-free paper.
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than
200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on
a foundation of principles that include responsibility to the communities we serve and where we live and work.
In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, eco-
nomic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper
specifications and procurement, ethical conduct within our business and among our vendors, and community and
charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.
Copyright © 2016 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be repro-
duced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechani-
cal, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher,
or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen-
ter, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the
Web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201)
748-6008, or online at: www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at: www.wiley.com/go/returnlabel. Outside of the
United States, please contact your local representative.
The inside back cover will contain printing identification and country of origin if omitted from this page. In
addition, if the ISBN on the back cover differs from the ISBN on this page, the one on the back cover is correct.
ISBN 978-1-119-05655-3
ISBN-BRV 978-1-119-05636-2
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
P R E FA C E
This book is an introduction to computer programming using Python that focuses on
the essentials—and on effective learning. Designed to serve a wide range of student
interests and abilities, it is suitable for a first course in programming for computer
scientists, engineers, and students in other disciplines. No prior programming expe-
rience is required, and only a modest amount of high school algebra is needed. For
pedagogical reasons, the book uses Python 3, which is more regular than Python 2.
Here are the book’s key features:
Present fundamentals first.
The book takes a traditional route, first stressing control structures, functions, proce-
dural decomposition, and the built-in data structures. Objects are used when appro-
priate in the early chapters. Students start designing and implementing their own
classes in Chapter 9.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Numerous Worked Examples demonstrate how to apply chap-
ter concepts to interesting problems.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
Algorithm Design (with pseudocode)
First Do It By Hand (doing sample
calculations by hand)
Flowcharts
Test Cases
Hand-Tracing
Storyboards
Solve a Simpler Problem First
Reusable Functions
Stepwise Refinement
Adapting Algorithms
Discovering Algorithms by
Manipulating Physical Objects
Tracing Objects
Patterns for Object Data
Thinking Recursively
Estimating the Running Time of
an Algorithm
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice oppor-
tunities, including automatically-graded programming exercises and skill-oriented
multiple-choice questions, are available online.
iii
Zgłoś jeśli naruszono regulamin