第一章 Python基础
第一章 Python基础
Programming
Fundamentals of Python: Data Structures, Second Edition
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except
for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Learning Objectives (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Learning Objectives (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Basic Program Elements
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Programs and Modules
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
An Example Python Program: Guessing a
Number (1 of 2)
>"""
Author: Ken Lambert
Plays a game of guess the number with the user.
"""
import random
def main():
"""Inputs the bounds of the range of numbers
and lets the user guess the computer’s number until
the guess is correct."""
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess: "))
if userNumber < myNumber:
print("Too small")
elif userNumber > myNumber:
print("Too large")
else:
print("You’ve got it in", count, "tries!")
break
if __name__ == "__main__":
main()
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
An Example Python Program: Guessing a
Number (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Editing, Compiling, and Running Python
Programs (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Editing, Compiling, and Running Python
Programs (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Program Contents
• Program comment
• Text ignored by the Python compiler
• Valuable to the reader as documentation
• End-of-line comment
• Begins with a # symbol and extends to the end of the current line
• Multiline comment
• A string enclosed in triple single quotes or triple double quotes
• Called docstrings to indicate that they can document major constructs
within a program
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Lexical Elements
• Lexical elements
• Types of words or symbols used to construct sentences
• Lexical items also include
• Identifiers (names)
• Literals (numbers, strings, and other built-in data structures)
• Operators
• Delimiters (quotation marks, commas, parentheses, square brackets,
and braces)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Spelling and Naming Conventions (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Syntactic Elements
• Syntactic elements
• Types of sentences (expressions, statements, definitions, and other
constructs) composed from lexical elements
• Python uses white space to mark the syntax of many types of
sentences:
• Indentation and line breaks
• This book uses an indentation width of four spaces in all Python
code
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Literals
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
String Literals (1 of 2)
• Enclose strings in
• Single quotes
• Double quotes
• Sets of three double quotes or three single quotes
• Character values are single-character strings
• The \ character is used to escape nongraphic characters such as
• Newline (\n) and tab (\t) or the \ character itself
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
String Literals (2 of 2)
• Example:
• print("Using double quotes")
• print('Using single quotes')
• print("Mentioning the word ‘Python’ by quoting it")
• print("Embedding a\nline break with n")
• print("""Embedding a
• line break with triple quotes""")
• Output:
Using double quotes
Using single quotes
Mentioning the word 'Python' by quoting it
Embedding a
line break with \n
Embedding a
line break with triple quotes
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Operators and Expressions (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Operators and Expressions (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Function Calls
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The print Function
• print
• Standard output function that displays arguments on the console
• Python automatically runs the str function on each argument to
obtain its string representation:
• Separates each string with a space before output
• By default
• print terminates its output with a newline
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The input Function
• input
• Waits for the user to enter text
• When user presses the Enter key,
• The function returns a string containing characters entered
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Type Conversion Functions and Mixed-Mode
Operations
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Variables and Assignment Statements
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Python Data Typing
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
import Statements
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Getting Help on Program Components
• To access help,
• Enter the function call help (<component>) at the shell prompt
• For example,
• help (abs) and help (math.sqrt) display documentation for the
abs and math.sqrt functions
• Calls of dir(int) and dir(math) list all the operations in the
int type and math module:
• You can then run help to get help on one of these operations
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Control Statements
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Conditional Statements (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Conditional Statements (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Loop Statements
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Strings and Their Operations
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Operators
• Comparison operators:
• When strings are compared, the pairs of characters at each position in
two strings are compared
• The + operator builds and returns a new string that contains the
characters of the two operands
• The subscript operator expects an integer in the range from 0 to
the length of the string minus 1:
"greater"[0] # Returns 'g'
• Slice operator is a variation of the subscript:
"greater"[:] # Returns "greater"
"greater"[2:] # Returns "eater"
"greater"[:2] # Returns "gr"
"greater"[2:5] # Returns "eat"
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Formatting Strings for Output (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Formatting Strings for Output (2 of 2)
• The format information for a data value of type float has the form:
%<field width>.<precision>f
• This example shows the output of a floating-point number
without, and then with, a format string:
>>>salary = 100.00
>>>print("Your salary is $" + str(salary))
Your salary is $100.0
>>>print("Your salary is $%0.2f" % salary)
Your salary is $100.00
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Object and Method Calls
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Built-In Python Collections and Their Operations
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Lists (1 of 2)
• List
• A sequence of zero or more Python objects
• Commonly called items
• Has a literal representation
• Uses square brackets to enclose items separated by commas
• Examples:
[] # An empty list
["greater"] # A list of one string
["greater", "less"] # A list of two strings
["greater", "less", 10] # A list of two strings and an int
["greater", ["less", 10]] # A list with a nested list
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Lists (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Tuples
• Tuple
• An immutable sequence of items
• Tuple literals enclose items in parentheses
• Essentially like a list without mutator methods
• A tuple with one item must still include a comma:
>>> (34)
34
>>> (34,)
(34)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Loops over Sequences
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Dictionaries
• Dictionary
• Contains zero or more entries
• Each entry associates a unique key with a value
• Keys are typically string or integers
• Values are any Python objects
• Examples:
{} # An empty dictionary
{"name":"Ken"} # One entry
{"name":"Ken", "age":67} # Two entries
{"hobbies":["reading", "running"]} # One entry, value
is a list
>>> for key in {"name":"Ken", "age":67}:
print(key)
name
age
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Searching for a Value
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Pattern Matching with Collections
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Creating New Functions
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Function Definitions
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Recursive Functions (1 of 2)
• Recursive function
• A function that calls itself
• To prevent a function from repeating itself indefinitely,
• It must contain at least one section statement that examines a condition
called a base case to determine whether to stop or to continue with a
recursive step
• Example of a definition of a function displayRange that prints
the numbers from a lower bound to an upper bound:
def displayRange(lower, upper):
"""Outputs the numbers from lower to upper."""
while lower <= upper:
print(lower)
lower = lower + 1
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Recursive Functions (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Nested Function Definitions
• Higher-order function
• A function that receives another function as an argument and applies it in
some way
• Python includes two built-in higher-order functions useful for
processing iterable objects:
• map and filter
map(str, oldList)
• Creates the iterable object containing the strings, and the code
newList = list(map(str, oldList))
• Creates a new list from that object
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Higher-Order Functions (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Creating Anonymous Functions with lambda
• Syntax of lambda:
lambda <argument list> : <expression>
• The code:
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Catching Exceptions
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Files and Their Operations
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Text File Output (1 of 2)
• String data are written to a file using the method write with the
file object:
• The write method expects a single string argument
• If you want the output text to end with a newline,
• You must include the escape character \n in the string
• The next statement writes two lines of text to the file:
• >>> f.write("First line.\nSecond line.\n")
• When all the outputs are finished, the file should be closed using
the method close, as follows:
• >>> f.close()
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Writing Numbers to a Text File
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Reading Text from a Text File (1 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Reading Text from a Text File (2 of 2)
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Reading Numbers from a File
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Reading and Writing Objects with pickle
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Creating New Classes
• Class
• Describes the data and the methods pertaining to a set of objects
• Provides a blueprint for creating objects and the code to execute when
methods are called on them
• Syntax of a Python class definition:
def <class name>(<parent class name>):
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for
use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.