# 1 基本程序要素

### Python 程序示例：猜数字

``````"""
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()

``````

``````Enter the smaller number: 1
Enter the larger number: 32
Too small
Too large
You’ve got it in 3 tries!

``````

``````python numberguess.py

``````

### 程序注释

``````# This is an end-of-line comment.

``````

### 字符串字面值

``````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""")

``````

``````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

``````

### 函数调用

``````min(5, 2) # Returns 2

``````

Python 包含了一些标准的函数，例如 abs 和 round。很多其他的函数，可以通过导入模块的方式而变得可用，稍后你将会看到这一点。

### input 函数（输入）

``````name = input("Enter the smaller number: ")

``````

### 类型转换函数和混合模式运算

``````radius = float(input("Radius: "))
print("The area is", 3.14 * radius ** 2)

``````

### 变量和赋值语句

PI = 3.1416

<identifier> = <expression>

``````minValue, maxValue = 1, 100

``````

``````a, b=b,a

``````

### import 语句

import 语句使得另一个模块中的标识符可以被一个程序所见到。这些标识符可能是对象名、函数名或类名。有几种方式可以表示一条 import 语句。最简单的方式是，导入一个模块名称，例如：

``````import math

``````

``````from math import sqrt
print(sqrt(2))

``````

``````from math import pi, sqrt
print(sqrt(2) * pi)

``````

# 2 控制语句

Python 包含了针对序列、条件式执行和迭代等情况的、常见的各种控制语句。语句的序列是一条接着一条编写的一组语句。一个序列中的每一条语句，都必须以相同的缩进开始。本节将会介绍条件式执行和迭代的控制语句。

# 条件语句

Python 的条件式语句的结构和其他语言中的条件式语句类似。关键词 if、elif 和else 是很重要的，冒号和缩进也同样重要。

``````if <Boolean expression>:
<sequence of statements>

``````

``````if <Boolean expression>:
<sequence of statements>
else:
<sequence of statements>

``````

``````if <Boolean expression>:
<sequence of statements>
elif <Boolean expression>:
<sequence of statements>
...
else:
<sequence of statements>

``````

``````if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

``````

### 使用 if name == "main"

``````if __name__ == "__main__":
main()

``````

### 循环语句

Python 的 while 循环语句的结构，类似于其他语言中的循环结构。其语法如下：

``````while <Boolean expression>:
<sequence of statements>

``````

``````product = 1
value = 1
while value <= 10:
product *= value
value += 1
print(product)

``````

``````product = product * value

``````

Python 包含了一个for 循环语句，以便更简洁地遍历值的一个序列。这条语句的语法如下：

``````for <variable> in <iterable object>:
<sequence of statements>

``````

``````product = 1
for value in range(1, 11):
product *= value
print(product)

``````

Python 程序员通常更喜欢使用一个 for 循环来遍历确定的范围的值或值的序列。当继续循环的条件是一个任意的布尔表达式的时候，程序员则使用 while 循环。

### 3字符串及其运算

#### 运算符

+运算符构建并返回一个新的字符串，它包含了两个运算数中的字符。

``````"greater"[0] # Returns "g"

``````

``````<a string>[<lower>:<upper>]

``````

``````"greater"[:] # Returns "greater"
"greater"[2:] # Returns "eater"
"greater"[:2] # Returns "gr"
"greater"[2:5] # Returns "eat"

``````

### 对象和方法调用

``````<object>.<method name>(<list of arguments>)

``````

``````"greater".isupper() # Returns False
"greater".upper() # Returns "GREATER"
"greater".startswith("great") # Returns True

``````

``````len("greater") # Is equivalent to "greater".__len__()
"great" + "er" # Is equivalent to "great".__add__("er")
"e" in "great" # Is equivalent to "great".__contains__("e")

``````

# 4内建 Python 集合及其操作

### 列表

``````[] # 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

``````

``````testList = [] # testList is []
testList.append(34) # testList is [34]
testList.append(22) # testList is [34, 22]
testList.sort() # testList is [22, 34]
testList.pop() # Returns 22; testList is [34]
testList.insert(0, 22) # testList is [22, 34]
testList.insert(1, 55) # testList is [22, 55, 34]
testList.pop(1) # Returns 55; testList is [22, 34]
testList.remove(22) # testList is [34]
testList.remove(55) # raises ValueError

``````

``````"Python is cool".split() #Returns[’Python’,’is’,’cool’]
" ".join(["Python","is","cool"]) #Returns’Python is cool’

``````

### 遍历序列

for 循环用来遍历一个序列（如字符串、列表或元组）中的项。例如，如下的代码段输出一个列表中的项：

``````testList = [67, 100, 22]
for item in testList:
print(item)

``````

``````testList = [67, 100, 22]
for index in range(len(testList)):
print(testList[index])

``````

### 字典

``````{} # An empty dictionary
{"name":"Ken"} # One entry
{"name":"Ken", "age":61} # Two entries
{"hobbies":["reading", "running"]} # One entry, value is a list

dic = {"name":"Ken", "age":61}
for key,value in dic.items():
print(key, value)

``````

# 5 函数

### 函数定义

Python 函数的定义语法是：

``````def <function name>(<list of parameters>):
<sequence of statements>

``````

``````def square(n):
"""Returns the square of n."""
result = n ** 2
return result

``````

``````first() # Raises a NameError (function undefined yet)
def first():
second() # Not an error, because not actually
print("Calling first.") # called until after second is defined
def second():
print("Calling second.")
first() # Here is where the call should go

``````

### 递归函数

``````def displayRange(lower, upper):
"""Outputs the numbers from lower to upper."""
while lower <= upper:
print(lower)
lower = lower + 1

``````

• 当 lower<=upper 的时候，循环体继续执行；
• 当函数执行的时候，lower 增加 1，但是 upper 不变。
等价的递归函数可以执行类似的基本操作，但是，用一条 if 语句替代了循环，用函数的递归调用替代了赋值语句。如下是做出这些修改后的代码：
``````def displayRange(lower, upper):
"""Outputs the numbers from lower to upper."""
if lower <= upper:
print(lower)
displayRange(lower + 1, upper)

``````

``````def ourSum(lower, upper):
"""Returns the sum of the numbers from lower thru upper."""
if lower > upper:
return 0
else:
return lower + ourSum(lower + 1, upper)

``````

### 类和对象

``````def <class name>(<parent class name>):
<class variable assignments>
<instance method definitions>

``````

``````"""
File: counter.py

Defines a Counter class for counting.
"""

class Counter(object):
"""Models a counter."""

# Class variable
instances = 0

#Constructor
def __init__(self):
"""Sets up the counter."""
Counter.instances += 1
self.reset()

# Mutator methods
def reset(self):
"""Sets the counter to 0."""
self._value = 0

def increment(self, amount = 1):
self._value += amount

def decrement(self, amount = 1):
"""Subtracts amount from the counter."""
self._value -= amount

# Accessor methods
def getValue(self):
"""Returns the counter's value."""
return self._value

def __str__(self):
"""Returns the string representation of the counter."""
return str(self._value)

def __eq__(self, other):
"""Returns True if self equals other

or False otherwise."""
if self is other: return True
if type(self) != type(other): return False
return self._value == other._value

``````

``````>>>from counter import Counter
>>>c1=Counter()
>>>print(c1)
0
>>>c1.getValue()0
>>>str(c1)
’0’
>>>c1.increment()
>>>print(c1)
1
>>>c1.increment(5)
>>>print(c1)
6
>>>c1.reset()
>>>print(c1)
0
>>>c2=Counter()
>>>Counter.instances
2
>>>c1==c1
True
>>>c1==0
False
>>>c1==c2
True
>>>c2.increment()
>>>c1==c2
False
>>>

``````

increment 和 decrement 方法使用默认的参数，这允许程序员来选择指定还是不指定这个量。Counter 类中的str方法覆盖了 object 类中的相同的方法。当把对象作为参数传递给 str 函数的时候，python 在该对象上运行str。当在一个对象上运行一个方法的时候，Python 首先在该对象自己的类中查找该方法的代码。如果没有在那里找到这个方法，Python 会在其父类中查找，依次类推。如果最终没有找到该方法的代码（在 object类中查找完了之后），Python 会抛出一个异常。

# 文件操作

### 文本文件的输出

``````34.6 22.33 66.75
77.12 21.44 99.01

``````

``````>>>f=open("myfile.txt",’w’)

``````

``````>>> f.write("First line.\nSecond line.\n")

``````

``````>>> f.close()

``````

### 将数字写入到一个文本文件

``````import random

f=open("integers.txt",'w')
for count in range(500):
number = random.randint(1, 500)
f.write(str(number) + "\n")
f.close()

``````

### 从文本文件读取文本

``````>>>f=open("myfile.txt",’r’)

``````

``````>>> text=f.read()
>>> text
’First line. \nSecond line. \n’
>>>print(text)
First line.
Second line.
>>>

``````

``````>>>f=open("myfile.txt",’r’)
>>>for line in f:
print(line)
First line.
Second line.
>>>

``````

``````>>>f=open("myfile.txt",’r’)
>>> while True: