第一部分 基础知识
第一章 起步
1.1 搭建编程环境
1.1.1 Python2和Python3
1.1.2 Hello World程序
print("Hello World!")
1.2 在不同操作系统中搭建Python编程环境
1.2.1 在Linux系统中搭建Python编程环境
1. 检查Python环境
$ python
Python 2.7.6
>>>
想要退出可以按Ctrl+D或执行exit()
要检查是否安装了Python3,可以尝试:
$ python3
2. 安装文本编译器
Geany $sudo apt-get install geany
3. 运行Hello World程序
如果安装多个版本Python,需要指定版本,即使用python3命令。
让Geany使用Python3:
python3 -m py_compile "%f"
4. 在终端会话中运行Python代码
1.2.2 在Windows系统中搭建Python编程环境
1. 安装Python
cmd中输入python查看是否安装
2. 启动Python终端会话
输入python后出现Python提示符:
>>>
3. 在终端会话中运行Python
>>>print("Hello Python World!")
Hello Python World!
>>>
4. 安装文本编译器
- 访问http://geany.org/
- 找到安装程序geany-1.25_setup.exe或类似的文件。
- 创建一个用于存储项目的文件夹,并将其命名为python_work
- 并将其命名为hello_world.py。扩展名.py告诉Geany,文件包含的是Python程序;它还让Geany知道如何运行该程序,并以有益的方式突出其中的代码。
5. 运行Hello World程序
选择菜单Build ▶Execute、单击Execute图标或按F5。
1.3 从终端运行Python程序
1.3.1 在Linux和OS X系统中从终端运行Python程序
~>cd Desktop/python_work/
~/Desktop/python_work>ls
hello_world.py
~/Desktop/python_work>python hello_world.py
Hello Python world!
1.3.2 在Windows系统中从终端运行Python程序
C:\>cd Desktop\python_work
C:\Desktop\python_work>dir
hello_world.py
C:\Desktop\python_work>python hello_world.py
Hello Python world!
第二章 变量和简单的数据类型
2.1 变量
message = "Hello Python world!"
print(message)
结果
Hello Python world!
再打印一条信息
message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)
结果
Hello Python world!
Hello Python Crash Course world!
2.1.1 变量的命名和使用
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message1,但不能将其命名为1message。
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
2.2 字符串
字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号,如下所示:
"This is a string."
'This is also a string.'
2.2.1 使用方法修改字符串的大小写
name = "ada lovelace"
print(name.title())
输出:
Ada Lovelace
在print()语句中,方法title()出现在这个变量的后面。
- 方法是Python可对数据执行的操作。
-
每个方法后面都跟着一对括号,这是因为方法通常需要额外的信息来完成其工作。这种信息是在括号内提供的。函数title()不需要额外的信息,因此它后面的括号是空的。
-
.title():把每个单词首字母大写,其余小写
- .upper():把每个字母全部改成大写
- .lower():把每个字母全部改成小写
2.2.2 合并(拼接)字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name+" "+last_name
print(full_name)
print("Hello,"+full_name.title()+"!")
message = "Hello,"+full_name.title()+"!"
print(message)
2.2.3 使用制表符或换行符来添加空白
在字符串中添加制表符,可使用字符组合\t
>>>print("Python")
Python
>>>print("\tPython")
Python
在字符串中添加换行符,可使用字符组合\n:
>>>print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
2.2.4 删除空白
Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白,可使用方法rstrip()。
>>>favorite_language = 'python '
>>>favorite_language
'python '
>>>favorite_language.rstrip()
'python'
>>>favorite_language
'python '
对变量favoritelanguage调用方法rstrip()后,这个多余的空格被删除了。然而,这种删除只是暂时的,接下来再次询问favoritelanguage的值时,你会发现这个字符串与输入时一样,依然包含多余的空白。
要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中:
>>>favorite_language = 'python '
>>>favorite_language = favorite_language.rstrip()
>>>favorite_language
'python'
剔除字符串开头的空白,或同时剔除字符串两端的空白。可分别使用方法lstrip()和strip():
>>>favorite_language = 'python '
>>>favorite_language.rstrip()
'python
>>>favorite_language.lstrip()
'python '
>>>favorite_language.strip()
'python'
2.3 数字
2.31 整数
>>>2+3
5
>>>3 - 2
1
>>>2 * 3
6
>>>3 / 2
1.5
Python使用两个乘号表示乘方运算:
>>>3 ** 2
9
>>>3 ** 3
27
Python还支持运算次序:
>>>2+3*4
14
>>>(2+3) * 4
20
2.3.2 浮点数
只需输入要使用的数字:
>>>0.1+0.1
0.2
>>>2 * 0.1
0.2
但需要注意的是,结果包含的小数位数可能是不确定的:
>>>0.2+0.1
0.30000000000000004
>>>3 * 0.1
0.30000000000000004
2.3.3 使用函数str()避免类型错误
例如:
age = 23
message = "Happy "+age+"rd Birthday!"
print(message)
上述代码打印会引发错误:这是一个类型错误,意味着Python无法识别使用的信息。在这个示例中,Python发现你使用了一个值为整数(int)的变量,但它不知道该如何解读这个值。
- Python知道,这个变量表示的可能是数值23,也可能是字符2和3。
- 可调用函数str(),它让Python将非字符串值表示为字符串:
age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)
这样,Python就知道要将数值23转换为字符串,进而在生日祝福消息中显示字符2和3:
Happy 23rd Birthday!
2.4 注释
在Python中,注释用井号(#)标识。井号后面的内容都会被Python解释器忽略:
# 向大家问好
print("Hello Python people!")
Hello Python people!
第三章 列表简介
3.1 列表是什么
相当于C中数组
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
如果打印出来打印:
['trek','cannondale','redline','specialized']
显然,这不是想要看到的输出。
3.1.1 访问列表元素
要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可:
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0])
当请求获取列表元素时,Python只返回该元素,而不包括方括号和引号:
trek
还可以对任何列表元素调用第2章介绍的字符串方法。例如,可使用方法title()让元素'trek'的格式更整洁:
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0].title())
- 索引是从0开始,而不是1!
3.1.2 使用列表中的各个值
例如,你可以使用拼接根据列表中的值来创建消息。
bicycles = ['trek','cannondale','redline','specialized']
message = "My first bicycle was a "+bicycles[0].title()+"."
print(message)
结果:
My first bicycle was a Trek.
3.2.1 修改列表元素
列表修改,与C语言数组修改相似:
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
3.2.2 在列表中添加元素
1.在列表末尾添加元素
使用方法append():
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
- 方法append()实现了动态创建列表。
2.在列表中插入元素
使用方法insert()可在列表的任何位置添加新元素。为此,需要指定新元素的索引和值。
motorcycles = ['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
3.2.3 从列表中删除元素
1.使用del语句删除元素
如果知道要删除的元素在列表中的位置,可使用del语句。
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
2.使用方法pop()删除元素
方法pop()可删除列表末尾的元素,并能够接着使用它。
- 术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
3.弹出列表中任何位置处的元素
可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
motorcycles = ['honda','yamaha','suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a '+first_owned.title()+'.')
del&pop() - 如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句; - 如果你要在删除元素后还能继续使用它,就使用方法pop()。
4.根据值删除元素
当不知道要从列表中删除的值所处的位置。如果只知道要删除的元素的值,可使用方法remove()。
motorcycles = ['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
使用remove()从列表中删除元素时,也可接着使用它的值。
- 注意 方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
3.3 组织列表
3.3.1 使用方法sort()对列表进行永久性排序
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
按字母顺序排列的,再也无法恢复到原来的排列顺序:
['audi','bmw','subaru','toyota']
还可以按与字母顺序相反的顺序排列列表元素,向sort()方法传递参数reverse=True:
cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
同样,对列表元素排列顺序的修改是永久性的:
['toyota','subaru','bmw','audi']
- 方法sort()按照ASCII值的大小进行排序,因此,当列表中元素相同时,基本都可以排序:
全为int:
num = [134,123,154,146]
num.sort()
print(num)
结果:
[123, 134, 146, 154]
大小写字母,按照码值排列:
alpha = ['C','B','d','A','a']
alpha.sort()
print(alpha)
结果:
['A', 'B', 'C', 'a', 'd']
字符数字和字母:
alnum = ['C','B','d','A','a','3','24']
alnum.sort()
print(alnum)
结果:
['24', '3', 'A', 'B', 'C', 'a', 'd']
3.3.2 使用函数sorted()对列表进行临时排序
cars = ['bmw','audi','toyota','subaru']
print(cars)
print(sorted(cars))
print(cars)
首先按原始顺序打印列表,再按字母顺序显示该列表。以特定顺序显示列表后,进行核实,确认列表元素的排列顺序与以前相同。
['bmw','audi','toyota','subaru']
['audi','bmw','subaru','toyota']
['bmw','audi','toyota','subaru']
如果要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。
- 注意 在并非所有的值都是小写时,按字母顺序排列列表要复杂些。
3.3.3 倒着打印列表
要反转列表元素的排列顺序,可使用方法reverse()。
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
- 注意,reverse()不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序:
['bmw','audi','toyota','subaru'] ['subaru','toyota','audi','bmw']
- 方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse()即可。
3.3.4 确定列表的长度
使用函数len()可快速获悉列表的长度。
>>>cars = ['bmw','audi','toyota','subaru']
>>>len(cars)
4
注意:索引-1总是返回最后一个列表元素
第4章操作列表
4.1 遍历整个列表
下面使用for循环来打印所有学号:
nums = ['202301','202301','202303','202304']
for num in nums:
print(num)
输出:
202301
202301
202303
202304
注意:for循环需要缩进以指示循环体。
4.1.1 深入地研究循环
Python将首先读取其中的第一行代码:
for num in nums:
这行代码让Python获取列表nums中的第一个值('202301'),并将其存储到变量num中。接下来,Python读取下一行代码:
print(num)
4.1.2 在for循环中执行更多的操作
在for循环中,想包含多少行代码都可以。在代码行for num in nums:后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。
nums = ['202301','202301','202303','202304']
for num in nums:
print("Attend:")
print(num+" is a shtudent's number")
输出:
Attend:
202301 is a shtudent's number
Attend:
202301 is a shtudent's number
Attend:
202303 is a shtudent's number
Attend:
202304 is a shtudent's number
4.1.3 在for循环结束后执行一些操作
在for循环后面,没有缩进的代码都只执行一次,而不会重复执行。
4.3 创建数值列表
4.3.1 使用函数range()
for value in range(1,5):
print(value)
输出:
1
2
3
4
在这个示例中,range()只是打印数字1~4,这是在编程语言中经常看到的差一行为的结果。函数range()让Python从指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5)。
4.3.2 使用range()创建数字列表
要创建数字列表,可使用函数list()将range()的结果直接转换为列表。如果将range()作为list()的参数,输出将为一个数字列表。
numbers = list(range(1,6))
print(numbers)
输出:
[1,2,3,4,5]
使用函数range()时,还可指定步长。例如,下面的代码打印1~10内的偶数:
even_numbers = list(range(2,11,2))
print(even_numbers)
输出:
[2,4,6,8,10]
使用函数range()几乎能够创建任何需要的数字集,例如,创建一个列表,其中包含前10个整数(即1~10)的平方:
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
输出:
[1,4,9,16,25,36,49,64,81,100]
为让这些代码更简洁,可不使用临时变量square,而直接将每个计算得到的值附加到列表末尾:
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
4.3.3 对数字列表执行简单的统计计算
>>>digits = [1,2,3,4,5,6,7,8,9,0]
>>>min(digits)
0
>>>max(digits)
9
>>>sum(digits)
45
4.3.4 列表解析
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。
squares = [value**2 for value in range(1,11)]
print(squares)
首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。
输出:
[1,4,9,16,25,36,49,64,81,100]
4.4 使用列表的一部分
4.4.1 切片
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。例如:要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素。
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
注意1:如果没有指定第一个索引,Python将自动从列表开头开始;要让切片终止于列表末尾,也可使用类似的语法。
注意2:负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的任何切片:
players = ['charles','martina','michael','florence','eli']
print(players[-3:])
4.4.2 遍历切片
players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
输出:
Here are the first three players on my team:
Charles
Martina
Michael
4.4.3 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
输出:
['pizza','falafel','carrot cake']
['pizza','falafel','carrot cake']
为核实我们确实有两个列表,下面在每个列表中都添加一种食品,并核实每个列表都记录了相应人员喜欢的食品:
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
输出:
['pizza','falafel','carrot cake','cannoli']
['pizza','falafel','carrot cake','ice cream']
倘若我们只是简单地将my_foods赋给friend_foods,就不能得到两个列表。
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods #这行不通
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
这里将my_foods赋给friend_foods,而不是将my_foods的副本存储到friend_foods。这种语法实际上是让Python将新变量friend_foods关联到包含在my_foods中的列表,因此这两个变量都指向同一个列表。鉴于此,当我们将'cannoli'添加到my_foods中时,它也将出现在friend_foods中;同样,虽然'ice cream'好像只被加入到了friend_foods中,但它也将出现在这两个列表中。
['pizza','falafel','carrot cake','cannoli','ice cream']
['pizza','falafel','carrot cake','cannoli','ice cream']
4.5 元组
有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
4.5.1 定义元组
元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
输出:
200
50
下面来尝试修改元组dimensions中的一个元素,看看结果如何:
dimensions = (200,50)
dimensions[0] = 250
由于试图修改元组的操作是被禁止的,因此Python指出不能给元组的元素赋值:
Traceback (most recent call last):
File "dimensions.py",line 3,in <module>
dimensions[0] = 250
TypeError:'tuple'object does not support item assignment
4.5.2 遍历元组中的所有值
像列表一样,也可以使用for循环来遍历元组中的所有值
4.5.3 修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量赋值:
dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
这次,Python不会报告任何错误,因为给元组变量赋值是合法的:
Original dimensions:
200
50
Modified dimensions:
400
100