Python2 编程入门

Python 交互模式

  • 进入
    • python 进入 python console
    • python -c command [arg] ...
      • usually advised to quote command in its entirety with single quotes.
    • Some Python modules as scripts: python -m module [arg] ...
  • 退出
    • Typing an end-of-file character (Control-D on Unix, Control-Z on Windows)
    • exit()
    • quit()
  • help 命令能显示简单的帮助

    help(可以是数据类型、变量)

    1
    2
    3
    4
    5
    6
    7
    8
      >>> help(int)
    
      Help on class int in module builtins:
    
      class int(object)
       |  int([x]) -> integer
       |  int(x, base=10) -> integer
      ... ...
    
  • dir 能查看 namespace 下面的 object 或 方法

    1
    2
      >>> dir(int)
      ['__abs__', '__add__', ... , 'to_bytes']
    
  • globals 和 locals 显示对应object的属性值

编码规则

  • Python Enhancement Proposal (PEP) 8

  • module / package 名称, 全小写 + 下划线
  • function 名称, 全小写 + 下划线
  • variable 名称, 全小写 + 下划线
  • Class 名称, 驼峰写法,例如, MyClass
  • 常量名称,全大写 + 下划线
  • 缩进,4个空格,不用tab
  • 比较表达式,不和True或False直接比较,例如, if my_var: if not my_var:

python 缩进

  • python 的缩进这么简单,一分钟让你学会

  • 和其它程序设计语言(如 Java、C 语言)采用大括号“{}”分隔代码块不同,Python 采用代码缩进和冒号( : )来区分代码块之间的层次
  • Python 对代码的缩进要求非常严格,同一个级别代码块的缩进量必须一样,否则解释器会报 SyntaxError 异常错误。
  • Python PEP8 编码规范,指导使用4个空格作为缩进。
  • 而实际开发,比较复杂的代码则会选择2个空格做为缩进,这样更易于阅读那些嵌套比较深的代码。
  • 建议tab符和空格做为缩进不能混用

  • 物理行和逻辑行
    • 物理行:代码编辑器中显示的代码,每一行内容是一个物理行。
    • 逻辑行:Python解释器对代码进行解释,一个语句是一个逻辑行。
    • 缩进是针对逻辑行的
    • 使用;号将两个或多个逻辑行合并成一个物理行。
    • 使用\号连接两个物理行。
    • 字典、列表等变量赋值语句,是可以直接书写为多个物理行的。
  • 缩进规则
    • 逻辑行的“首行”需要顶格,即无缩进
    • 相同逻辑层保持相同的缩进
    • :标记一个新的逻辑层, 增加缩进:进入下一个代码层,减少缩进:返回上一个代码层

Python 命令行

命令行参数

脚本名称和参数都放在 sys module 的 argv 变量。

  • The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string.
  • When the script name is given as ‘-‘ (meaning standard input), sys.argv[0] is set to ‘-‘.
  • When -c command is used, sys.argv[0] is set to ‘-c’.
  • When -m module is used, sys.argv[0] is set to the full name of the located module.

接受用户输入

1
2
3
4
5
6
7
8
name = input("Name? ")
# >>> Name? Jane
>>> print(name)
# >>> Jane
age = int(input("Age? "))
# >>> Age? 28
print(age)
# >>>28

变量

  • 实际python中所有数据类型其实都是对象,变量名实质是对象的引用
  • 变量名大小写敏感

  • 例子: 变量名实质是对象的引用
1
2
3
4
5
6
7
# 目标实例不可修改
a = 1
b = a
c = b
b = 5
print(a, b, c)
# >>> 1 5 1
1
2
3
4
5
6
7
# 目标实例可修改
a = [1, 2, 3]
b = a
c = b
b[1] = 5
print(a, b, c)
# >>> [1, 5, 3] [1, 5, 3] [1, 5, 3]

数据类型 Data Types

Built-in data types

  • 数值类型
    • integer
    • float
    • complex numbers
    • Boolean
  • 集合类型
    • List
    • Tuple
    • Dictionary
    • Set
  • String

None 值

  • None 用来表示空值。
  • Python 系统中的 None 是个单例,只有一个实例。

数值类型

  • 运算符号: + - * / 加减乘除、 ** 指数运算、% 求模
  • integer 没有大小限制,除非内存不够
  • complex number ,即 复数,如: 39 + 3i
  • cmath 库包含 complex number 的功能函数,其他数值计算的功能包含在 math 库,例如三角函数、双曲函数等。
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> x = 5 + 2 - 3 * 2
>>> x
1
>>> 5 / 2
2.5
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 ** 8
256
>>> 1000000001 ** 3
1000000003000000003000000001

Boolean

Boolean 实际就是整数: 1 (True) and 0 (False)

1
2
3
4
5
6
7
8
>>> x = False
>>> x
False
>>> not x
True
>>> y = True * 2
>>> y
2

Complex numbers

Complex numbers consist of both a real element and an imaginary element, suffixed with j.

complex number 的例子

1
2
3
4
5
6
7
8
9
10
>>> (3+2j) ** (2+3j)
(0.6817665190890336-2.1207457766159625j)
>>> x = (3+2j) * (4+9j)
>>> x
 B
(-6+35j)
>>> x.real
-6.0
>>> x.imag
35.0

常用功能函数

1
2
3
4
5
>>> round(3.49)
3
>>> import math
>>> math.ceil(3.49)
4

集合类型

Lists

  • 一个列表可以包含各种类型的 object。
  • 可以使用 0-n 的单个索引取值,也可以使用开始序号:结束序号来取出一个子列表
  • len(the-list) 返回列表长度。
1
2
3
4
[]
[1]
[1, 2, 3, 4, 5, 6, 7, 8, 12]
[1, "two", 3, 4.0, ["a", "b"], (5,6)]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> x = ["first", "second", "third", "fourth"]
>>> x[0]
'first'
>>> x[2]
'third'
>>> x[-1]
'fourth'
>>> x[-2]
'third'
>>> x[1:-1]
['second', 'third']
>>> x[0:3]
['first', 'second', 'third']
>>> x[-2:-1]
['third']
>>> x[:3]
['first', 'second', 'third']
>>> x[-2:]
['third', 'fourth']

Tuples

和 List 类似,但不可改动。

1
2
3
4
()
(1,)                  # 1个元素的tuple,逗号是必须的
(1, 2, 3, 4, 5, 6, 7, 8, 12)
(1, "two", 3L, 4.0, ["a", "b"], (5, 6))

list 转换为 tuple

1
2
x = [1, 2, 3, 4]
y = tuple(x)       #(1, 2, 3, 4)

Dictionary

  • Dictionary 就是 key-value 数组。
  • key必须是不可修改的数据类型,包括数值、字符串和tuple等。
  • len() 返回键值对数目。
  • del() 用来删除键值对。
1
2
3
4
5
6
7
8
9
10
11
12
13
x = {1: "one", 2: "two"}
x["first"] = "one"
x[("Delorme", "Ryan", 1995)] = (1, 2, 3)

>>> list(x.keys())
['first', 2, 1, ('Delorme', 'Ryan', 1995)]

>>> x[1]
'one'
>>> x.get(1, "not available")
'one'
>>> x.get(4, "not available")
'not available'

Set 集合

  • 元素唯一
1
2
3
4
5
6
7
8
9
10
>>> x = set([1, 2, 3, 1, 3, 5])
 b
>>> x
{1, 2, 3, 5}

>>> 1 in x
True
>>> 4 in x
False
>>>

String 字符串

  • 单引号和双引号,都可以作为字符串分隔符。
  • 三引号 “”“…””” 用来界定多行字符串文本
  • string 不可修改。
  • 支持 \ 转移字符,如: "\tThis (\string\) starts with a \"tab\"."
1
2
3
4
5
"A string in double quotes can contain 'single quote' characters."
'A string in single quotes can contain "double quote" characters.'
'''\tA string which starts with a tab; ends with a newline character.\n'''
"""This is a triple double quoted string, the only kind that can
contain real newlines."""
1
2
3
4
5
6
7
8
9
10
11
12
>>> x = "live and     let \t    \tlive"

>>> x.split()
['live', 'and', 'let', 'live']

>>> x.replace("     let \t    \tlive", "enjoy life")
'live and enjoy life'

>>> import re
>>> regexpr = re.compile(r"[\t ]+")
>>> regexpr.sub(" ", x)
'live and let live'

debug

print

1
2
3
4
5
6
7
8
9
e = 2.718
x = [1, "two", 3, 4.0, ["a", "b"], (5, 6)]

print("The constant e is:", e, "and the list x is:", x)

# >>> The constant e is: 2.718 and the list x is: [1, 'two', 3, 4.0, ['a', 'b'], (5, 6)]

print("the value of %s is: %.2f" % ("e", e))
# >>> the value of e is: 2.72

文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> f = open("myfile", "w")
>>> f.write("First line with necessary newline character\n")
>>> f.write("Second line to write to the file\n")
>>> f.close()

>>> f = open("myfile", "r")
>>> line1 = f.readline()
>>> line2 = f.readline()
>>> f.close()

>>> print(line1, line2)
First line with necessary newline character
Second line to write to the file

>>> import os
>>> print(os.getcwd())
c:\My Documents\test
>>> os.chdir(os.path.join("c:\\", "My Documents", "images"))
>>> filename = os.path.join("c:\\", "My Documents", "test", "myfile")
>>> print(filename)
c:\My Documents\test\myfile

>>> f = open(filename, "r")
>>> print(f.readline())
First line with necessary newline character
>>> f.close()

控制流 Control Flow

用于判断的 Boolean 值,比较宽泛,

False 判断可以是 False,0, nil,空值(如空列表[]、空字符串); 其他都可当作 True 。

  • 操作符包含:

  • comparison operator: <, <=, ==, >, >=, !=, is, is not, in, not in
  • logical operator: and, not, or

if-elif-else

1
2
3
4
5
6
7
8
9
10
11
x = 5
if x < 5:
    y = -1
    z = 5
elif x > 5:
    y = 1
    z = 11
else:
    y = 0
    z = 10
print(x, y, z)

while loop

1
2
3
4
5
6
7
8
9
10
11
u, v, x, y = 0, 0, 100, 30
while x > y:
    u = u + y
    x = x - y
    if x < y + 2:
        v = v + x
        x = 0
    else:
        v = v + y + 2
        x = x - y - 2
print(u, v)

for 循环

1
2
3
4
5
6
7
item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70]
for x in item_list:
    if not isinstance(x, int):
        continue
    if not x % 7:
        print("found an integer divisible by seven: %d" % x)
        break

Function 函数

  • 如果没发现 return ,python 默认返回 None Value
  • 调用函数,可以使用参数名,指定值
  • 最后一个函数参数,如果指定成带星号,如*rest_args,剩余的实参会一股脑打包成tuple,赋给这个参数。
  • 最后一个函数参数,如果指定成带2个星号,如**rest_args,剩余的实参会一股脑打包成 dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def funct1(x, y, z):
    value = x + 2*y + z**2
    if value > 0:
        return x + 2*y + z**2
    else:
        return 0

>>> u, v = 3, 4
>>> funct1(u, v, 2)
15
>>> funct1(u, z=v, y=2)  # 调用函数,可以使用参数名,指定值
23

def funct2(x, y=1, z=1):   # 定义参数的缺省值
    return x + 2 * y + z ** 2

>>> funct2(3, z=4)
21

def funct3(x, y=1, z=1, *tup):  # 最后一个函数参数,如果指定成带星号,剩余的实参会一股脑打包成tuple,赋给这个参
    print((x, y, z) + tup)

>>> funct3(2)
(2, 1, 1)
>>> funct3(1, 2, 3, 4, 5, 6, 7, 8, 9)
(1, 2, 3, 4, 5, 6, 7, 8, 9)

def funct4(x, y=1, z=1, **kwargs):  # 最后一个函数参数,如果指定成带2个星号,剩余的实参会一股脑打包成 dictionary
    print(x, y, z, kwargs)
>>> funct4(1, 2, m=5, n=9, z=3)
1 2 3 {'n': 9, 'm': 5}

Exceptions try-except-else-finally 异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class EmptyFileError(Exception):
    # 定义了一个错误类
    pass
filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"]
for file in filenames:
    try:
        f = open(file, 'r')
        line = f.readline()
        if line == "":
            f.close()
        raise EmptyFileError("%s: is empty" % file)
    except IOError as error:
        print("%s: could not be opened: %s" % (file, error.strerror)
    except EmptyFileError as error:
        print(error)
    else:
        # else 代码块可选,如果try块中没发生exception,则执行
        print("%s: %s" % (file, f.readline()))
    finally:
        # 可选,不管try块中有无生exception,都执行
        print("Done processing", file)

Context handling

try-except-finally 更优雅的是使用 context manager(关键词 with)

1
2
3
4
5
6
# 使用 with 和 context manager 读取文件内容
# 这里 context manager 是预定义的,自动清除打开的file
filename = "myfile.txt"
with open(filename, "r") as f:
    for line in f:
        print(f)

上面代码等同于:

1
2
3
4
5
6
7
8
9
filename = "myfile.txt"
try:
    f = open(filename, "r")
    for line in f:
        print(f)
except Exception as e:
    raise e
finally:
    f.close()

Module

  • 模块文件放到模块搜索路径即可。
  • 模块搜索路径,从 sys.path 查看
  • package 的概念: 将多个相关module文件放到一个文件夹下,就可以归拢为一个package,import 的时候使用: package.subpackage.module

  • File wo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""wo module. Contains function: words_occur()"""

# interface functions
def words_occur():
    """words_occur() - count the occurrences of words in a file."""
    # Prompt user for the name of the file to use.
    file_name = input("Enter the name of the file: ")
    # Open the file, read it and store its words in a list.
    f = open(file_name, 'r')
    word_list = f.read().split()
    f.close()

    # Count the number of occurrences of each word in the file.
    occurs_dict = {}
    for word in word_list:
        # increment the occurrences count for this word
        occurs_dict[word] = occurs_dict.get(word, 0) + 1
    # Print out the results.
    print("File %s has %d words (%d are unique)" \
        % (file_name, len(word_list), len(occurs_dict)))
    print(occurs_dict)

if __name__ == '__main__':
    words_occur()

wo.py 放到 module 搜索路径中,就可以 import 使用了:

1
2
import wo
wo.words_occur()

Object-oriented programming

  • File sh.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""sh module. Contains classes Shape, Square and Circle"""
class Shape:
    """Shape class: has method move"""
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def move(self, deltaX, deltaY):
        self.x = self.x + deltaX
        self.y = self.y + deltaY

class Square(Shape):
    """Square Class:inherits from Shape"""
    def __init__(self, side=1, x=0, y=0):
        Shape.__init__(self, x, y)
        self.side = side

class Circle(Shape):
    """Circle Class: inherits from Shape and has method area"""
    pi = 3.14159
    def __init__(self, r=1, x=0, y=0):
        Shape.__init__(self, x, y)
        self.radius = r
    def area(self):
        """Circle area method: returns the area of the circle."""
        return self.radius * self.radius * self.pi
    def __str__(self):
        return "Circle of radius %s at coordinates (%d, %d)" % (self.radius, self.x, self.y)
1
2
3
4
5
6
7
8
9
import sh
c1 = sh.Circle()
c2 = sh.Circle(5, 15, 20)

print(c1)
# >>> Circle of radius 1 at coordinates (0, 0)

print(c2)
# >>> Circle of radius 5 at coordinates (15, 20)