第一章 起步

1.变量

1.1 变量规范

  • 只能包含字母、数字、下划线。可以字母或下划线作为开头,而不能用数字
  • 变量名不能包含空格

1.2 例子

  1. message = "hello python world!"
  2. print(message)

添加一个名为message的变量,并且存储了为“Hello python world”的文本值

第二章 变量和简单数据类型

python常用的内置数据类型

Number(数字)、String(字符串)、List(列表)、Tuple(元组)、Set(集合)、Dictionary(字典)

Python中有3种不同的数字类型

int(整型)、float(浮点型)、complex(复数类型)

2.字符串

“This is a string.”

‘This is also a string’

2.1 使用方法修改字符串大小写

  1. name = '"ada lovelace"
  2. print(name.title()) #首字母大写方法

输出Ada Lovelace

  1. print(name.upper()) #全大写方法

输出 ADA LOVELACE

  1. print(name.lower()) #全小写方法

输出ada lovelace

2.2 合并(拼接)字符串

  1. first_name = 'ada'
  2. last_name = 'lovelace'
  3. full_name = first_name + ' ' + last_name #使用 + 来合并字符串
  4. print (full_name)
  5. print("Hello , " + full_name.title() + "!")#通过合并字符串(拼接)使用存储在变量中的信息来创造完整的消息
  6. message = "hello , " + full_name.title() + "!"#可以将拼接创造的消息存储在变量中打印出
  7. print(message)

2.3 使用制表符或换行符添加空白

\t 制表符

  1. print("python")
  2. #输出
  3. #python
  4. print("\tPython")
  5. #输出
  6. # python

\n换行符

  1. print("Languages:\nPython\nC\nJavaScript")
  2. #输出
  3. # Languages:
  4. # Python
  5. # C
  6. # JavaScript

2.4 删除空白

  • 确保字符串末尾没有空白——使用方法rstrip(),调用方法时多余的空格被删除,但是删除只是暂时的。

    1. favorite_language = 'python '
    2. print(favorite_language.rstrip())


    输出:python

  • 删除字符串开头lstrip()、两端strip()的空白

  1. favorite_language = ' python '
  2. print(favorite_language.rstrip())

' python'

  1. print(favorite_language.lstrip()) #去头

'python '

  1. print(favorite_language.strip()) #去两端

'python'

3.数字

3.1 整数

可以使用不同的进制来表示

  • 不加任何前缀为十进制整数
  • 加前缀0o为八进制整数
  • 加前缀0x则为十六进制整数
    加减乘除:
  1. print(2+3)

5

  1. print(3-2)

1

  1. print(3 * 2)

6

  1. print(3 / 2)

1.5

乘方运算

  1. print(3 ** 2)

9

  1. print(3 ** 3)

27

Booleam类型:

整型的子类型

使用函数可将其他类型的数据转为布尔类型,当给bool函数传入下列参数时将其返回false

3.2 浮点数

python中,带小数点的数字都称为浮点数(使用C语言中的double类型实现)

但包含小数位数可能是不确定的

  1. print(0.2 + 0.1)

0.300000000000004

3.3 使用函数str()避免类型错误

  1. age = 23
  2. message = "Happy " + str(age) + "rd Birthday!"
  3. print(message)

将数值23转换为字符串

3.4 python 2中的整数

  1. print(3 / 2)

1

返回的结果为1,而不是1.5。Python2中整数除法的结果只包含整数部分,小数部分被删除,计算整数结果时,将小数部分直接删除

要避免这种情况,必需一个操作数是浮点数

  1. print3.0 / 2

1.5

4.注释

注释用井号(#)标识,井号后的内容都会被解释器忽略

# 向大家问好

第三章 列表简介

3.1 列表的含义

列表: 由一系列按特定顺序排列的元素组成

用方括号([])来表示列表,并用逗号来分割其中的元素

  1. bicycles = [ 'trek' , 'cannondale' , 'redline' , ' specialized ']
  2. print(bicycles) #打印出列表,包含方括号
  3. ['trek' , 'cannondale' , 'redline' , 'specialized ']

3.1.1 访问列表元素

指出列表的名称,再指出元素的索引,并将其放在方括号中

  1. bicycles = [ 'trek' , 'cannondale' , 'redline' , ' specialized ']
  2. print(bicycles[0])
  3. trek##输出trek
  4. print(bicycles[0].title()) #让trek的格式更整洁

3.1.2 索引从0而不是1开始

访问索引1和3处的自行车

  1. bicycles = ['trek', 'cannodale ', 'redline' ,'specialized' ]
  2. print(bicycles[1])
  3. print(bicycles[3])

3.1.3 使用列表中的各个值

  1. bicycles = ['trek', 'cannodale ', 'redline' ,'specialized' ]
  2. message = "My first bicycle was a " + bicycles[0].title() + "."
  3. print(message)

使用bicycles[0]的值生成了一个句子,并将其存储在变量message中

输出My first bicycle was a trek

3.2 修改、添加和删除元素

3.2.1 修改列表元素

有一个摩托车列表,其中的第一个元素为’honda’,计划进行修改

  1. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]
  2. print(motorcycles)
  3. motorcycles[0] = ' ducati '
  4. print(motorcycles)

输出结果分别为

[‘honda’ , ‘yamaha’ , ‘suzuki’]

[‘ducati’ ,’ yamaha’ , ‘suzuki’]

3.2.2 在列表中添加元素

1.在列表末尾添加元素

  1. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]
  2. print(motorcycles)
  3. motorc.append(' ducati ')
  4. print(motorcycles)

输出结果

[‘honda’ , ‘yamaha’ , ‘suzuki’]

[‘honda’ , ‘yamaha’ , ‘suzuki’ , ‘ducati’]

方法append()将元素添加到了列表末尾,而不影响列表中的其他元素

2.在列表中插入元素

  1. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]
  2. motorcycles.insert(0, 'ducati)
  3. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]

输出结果

[‘ducati’ , ‘honda’ ,’yamaha’ , ‘suzuki’]

3.2.3 从列表中删除元素

1.使用del语句删除元素

知道删除的元素在列表中的位置,使用del语句

  1. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]
  2. print(motorcycles)
  3. del motorcycles[0]#使用del删除了列表中的第一个元素'honda'
  4. print(motorcycles)

输出结果

[ ‘honda’ , ‘yamaha’ , ‘suzuki’ ]

[’yamaha‘ , ‘suzuki ‘]

使用del语句进行删除后,再也无法访问该值

2.使用方法pop()删除元素

方法pop()可删除列表末尾的元素,并让你能够接着使用它

下面从列表中弹出一款摩托车

  1. motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]
  2. print(motorcycles)#打印列表
  3. popped_motorcycles = motorcycles.pop()#弹出一个值,并将其存储到popped_motorcycle
  4. print(motorcycles)#打印表,证实从中删除了一个值
  5. print(popped_motorcycle)#打印弹出的值,以证明依然能够访问到被删除的值

输出结果

[‘honda’ , ‘yamaha’ ,’suzuki’]

[‘honda’ ,’ yamaha’]

suzuki

假设列表中摩托车按购买时间排列,就可使用方法pop()打印一条消息,指出最后购买的是哪款摩托车

  1. motorcycles = ['honda' , 'yamaha' , 'suzuki']
  2. last_owned = motorcycles.pop()
  3. print("The last motorcycle I owned was a " + last_owned.title + ".")

输出结果

The last motorcycle I owned was a Suzuki

3.弹出列表中任何位置处的元素

用pop(n),删除列表中位于第n+1个位置的元素

  1. motorcycles = ['honda' , 'yamaha' , 'suzuki']
  2. first_owned = motorcycles.pop(0)
  3. print("The first motorcycle I owned was a " + last_owned.title + ".")

输出结果

The first motorcycle I owned was a Honda

总结:直删不用用del,删了还用用pop()

4.根据值删除元素

只知道要删除的元素的值,使用方法remove()

eg:在列表中删除值’ducati’

  1. motorcycles = ['honda' , 'yamaha' , 'suzuki','ducati']
  2. motorcycles.remove('ducati')
  3. print(motorcycles)

输出结果

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

[‘honda’, ‘yamaha’, ‘suzuki’]

使用remove()删除元素时,可以接着使用它的值

  1. motorcycles = ['honda' , 'yamaha' , 'suzuki','ducati']#定义列表
  2. print(motorcycles)
  3. too_expensive = 'ducati'#将'ducati'存储到too_expensive中
  4. motorcycles.remove(too_expensive)#删除列表中的ducati
  5. print(motorcycles)
  6. print('\nA ' + too_expensive.title() + " is too expensive for me.")

输出结果

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

[‘honda’, ‘yamaha’, ‘suzuki’]

A Ducati is too expensive for me.

remove()只删除第一个指定的值

3.3组织列表

以特定的顺序呈现信息、保留聊表元素最初的排列顺序

3.3.1 使用方法sort()对列表进行永久排序

按字母顺序进行排列

  1. cars = ['bmw' , 'audi' , 'toyota' , 'subaru']
  2. cars.sort()
  3. print(cars)

方法sort()永久性地改变了列表元素的排列顺序

输出结果

[‘audi’, ‘bmw’, ‘subaru’ ,’toyota’]

按与字母相反顺序来排列列表元素

  1. cars = ['bmw' , 'audi' , 'toyota' , 'subaru']
  2. cars.sort(reverse=True)
  3. print(cars)

输出结果

[‘toyota’, ‘subaru’, ‘bmw’, ‘audi’]

3.3.2 使用sorted()对列表进行临时排序

保留列表元素原来的排列顺序,同时以特定的顺序呈现 使用函数sorted()

  1. cars = ['bmw', 'audi', 'toyota', 'subaru']
  2. print("Here is the original list:")
  3. print(cars)
  4. print("\nHere is the sorted list:")
  5. print(sorted(cars)) #临时排序
  6. print("\nHere is the original list again:")
  7. print(cars

输出结果

Here is the original list:

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

Here is the sorted list:

[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]

Here is the original list again:

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

3.3.3 倒着打印列表

翻转列表元素的排序顺序,使用方法reverse()

  1. cars = ['bmw', 'audi', 'toyota', 'subaru']
  2. print(cars)
  3. cars.reverse()
  4. print(cars)

输出结果

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

[‘subaru’, ‘toyota’, ‘audi’, ‘bmw’]

reverse()不是按字母顺序相反的顺序进行排列,而是反转列表元素的排列顺序,且永久的修改排列顺序,但随时可恢复到原来的排列顺序

3.3.4 确定列表的长度

使用函数len()可快速获悉列表长度

  1. cars = ['bmw' , 'audi' , 'toyota' ,'subaru']
  2. len(cars)

4

3.4 使用列表时避免索引错误

需要访问最后一个列表元素时,都可以使用索引-1

  1. motorcycles = ['honda' , 'yamaha','suzuki']
  2. print(motorcycles[-1])

‘suzuki’

第四章 操作列表

4.1 遍历整个列表

需要对列表中的每个元素都执行相同的操作时,可使用Python的for循环

eg: 使用for循环来打印魔术师名单中的所有名字:

  1. magicians = ['alice', 'david' , 'carolina']
  2. for magician in magicians: #定义一个for循环,从列表magicians中取出一个名字,并将其存储在变量magician中
  3. print(magician)#注意空格

输出结果

alice

david

carolina

4.1.1 深入地研究循环

在前面的magicians.py中使用的简单循环中,Python将首先读取其中的第一行代码:

for magician in magicians:

这行代码让Python获取列表magicians 中的第一个值(’alice’ ),并将其存储到变量magician 中。接下来,Python读取下一行代码:

  1. print(magician)

它让Python打印magician 的值——依然是’alice’ 。鉴于该列表还包含其他值,Python返回到循环的第一行:

  1. for magician in magicians:

Python获取列表中的下一个名字——‘david’ ,并将其存储到变量magician 中,再执行下面这行代码:

  1. print(magician)

Python再次打印变量magician 的值——当前为’david’ 。接下来,Python再次执行整个循环,对列表中的最后一个值——‘carolina’ 进行处理。至此,列表中没有其他的值了,因此Python接着执行程序的下一行代码。在这个示例中,for 循环后面没有其他的代码,因此程序就此结束。

对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次, 且通常速度非常快。

4.1.2 在for循环中执行更多的操作

eg:对于每位魔术师,都打印一条消息:

  1. magicians = ['alice' , 'david' , 'carolina']
  2. for magician in magicians:`
  3. print(magician.title() + ", that was a great trick!" )

输出结果:

Alice, that was a great trick!

David, that was a great trick!

Carolina, that was a great trick!

4.1.3 在for循环结束后执行一些操作

在for循环结束后,需提供总结性输出或者接着执行程序必须完成的其他任务

  1. magicians = ['alice', 'david', 'carolina']
  2. for magician in magicians:
  3. print(magician.title() + ", that was a great trick!")`
  4. print("I can't wait to see your next trick, " + magician.title() + ".\n")
  5. print("Thank you, everyone. That was a great magic show!") #总结性语句

输出结果

Alice, that was a great trick!

I can’t wait to see your next trick, Alice.

David, that was a great trick!

I can’t wait to see your next trick, David.

Carolina, that was a great trick!

I can’t wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

4.2 避免缩进错误

4.2.1 忘记缩进

通常,将紧跟在for 语句后面的代码行缩进,可消除这种缩进错误。

4.2.2 忘记缩进额外的代码行

试图在循环中执行多项任务,却忘记缩进其中的一些代码行时,就会出现这种情况。

例如,如果忘记缩进循环中的第2行代码(它告诉每位魔术师,我们期待他的下一次表演),就会出现这种情况:

4.3 创建数值列表

4.3.1 使用函数range()

  1. for value in range (1,5):
  2. print(value)

打印结果:

1

2

3

4

range()只是打印数字1~4,函数range()让python从指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值

需要打印1~5 需要使用range(1,6)

  1. for value in range(1,6)
  2. print(value)

打印结果

1

2

3

4

5

4.3.2 使用range()创建数字列表

eg:使用list()将range()的结果直接转换为列表

  1. numbers = list(range(1,6))
  2. print(numbers)

结果如下

[1,2,3,4,5]

使用range()时,指定步长。

eg:打印1~10内的偶数

  1. event_numbers = list(range(2,11,2))
  2. print(event_numbers)

range()从2开始数,不断的加2,直到达到或超过最终值11

eg:创建一个列表,包含前十个整数的平方

  1. squares = []#创建空列表
  2. for value in range(1,11): #让函数range()遍历1~10
  3. square = value**2 #计算当前值的平方,存储到变量square中
  4. squares.append(square) #将新计算的平方值附加到列表squares末尾
  5. print(squares) #打印列表squares
  1. squares = []
  2. for value in range(1,11):
  3. squares.append(value**2) #不使用临时变量square 而直接将每个计算得到的值附加到列表末尾
  4. print(squares)

4.3.3 对数字列表执行简单的统计计算

  1. digits = [1,2,3,4,5,6,7,8,9,0]
  2. print(min(digits)) #输出最小值
  3. print(max(digits)) #输出最大值
  4. print(sum(digits)) #输出和

4.3.4 列表解析

列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素

  1. squares = [value**2 for value in range(1,11)]
  2. print(squares)
  • 先指定一个描述性的列表名
  • 制定一个左方括号,并定义一个表达式(value**2),用于生成存储到列表中的值
  • 编写一个for循环(for value in range(1,11)将值1~10提供给表达式value**2),用于给表达式提供值,再加上右方括号

4.4 使用列表的一部分

处理列表的所有元素

4.4.1 切片

创建切片,可指定使用的第一个元素和最后一个元素的索引,在到达指定的第二个索引前面的元素后停止

  1. player = ['charles','martina','michael','florence','eli']
  2. print(player[0:3])#输出第1~3

输出结果

[‘charles’, ‘martina’, ‘michael’]

只包含三名队员

如果没有制定第一个索引,将从列表开头开始提取:

  1. player = ['charles','martina','michael','florence','eli']
  2. print(player[:4])#输出前4

输出结果

[‘charles’, ‘martina’, ‘michael’, ‘florence’]

让列表终止于列表末尾:

提取从第三个元素到末尾的所有元素,可将起始索引指定为2,并省略终止索引:

  1. player = ['charles','martina','michael','florence','eli']
  2. print(player[2:])

输出结果为从第3个元素到列表末尾的所有元素

[‘michael’, ‘florence’, ‘eli’]

输出最后3个元素:

  1. print(player[-3:])

输出结果同上。

4.4.2 遍历切片

遍历列表的部分原始,在for循环中使用切片

eg:遍历前三名队员,并打印他们的名字

  1. players = ['charles','martina','michael','florence','eli']
  2. print("Here are the first three palyers on my team:")
  3. for player in player[:3]:#只遍历前三名队员
  4. print(player.title())

输出结果:

Here are the first three palyers on my team:
Charles
Martina
Michael

4.4.3 复制列表

需要既有列表创建全新的列表

可创建一个包含整个列表的切片:方法为同时省略起始索引和终止索引([:]),创建一个始于第一个元素终于最后一个元素的切片

  1. my_foods = ['pizza','falafel','caroot cake']
  2. friend_foods = my_foods[:]
  3. print("My favorite foods are:")
  4. print(my_foods)
  5. print("\nMy friends's favorite foods are:")
  6. print(friend_foods)

输出结果:

My favorite foods are:
[‘pizza’, ‘falafel’, ‘caroot cake’]

My friends’s favorite foods are:
[‘pizza’, ‘falafel’, ‘caroot cake’]

4.5 元组

元组是有序且不可更改的集合。

创建一系列不可修改的元素,不能修改的值-不变的,不可变的列表-元组

4.5.1 定义元组

用圆括号来标识

  1. di = (200,50)
  2. print(di[0])
  3. print(di[1])

4.5.2 遍历元组中所有的值

  1. for d in di:
  2. print(d)

4.5.3 修改元组变量

虽然不可修改元组的元素,但可以给存储元组的变量赋值:

重新定义整个元组

  1. di = (200,50)
  2. print("Original dimensions: ")
  3. for d in di:
  4. print(d)
  5. di = (400,100)
  6. print("\nModified dimensions: ")
  7. for ds in di :
  8. print(ds)

4.6 代码格式

4.6.1 格式设置指南

代码易于编写/便于阅读->大多数程序员选择便于阅读

4.6.2 缩进

每级缩进都使用四个空格

通常使用制表符而不是空格来进行缩进

4.6.3 行长

建议每行不超过80字符

4.6.4 空行

要讲程序的不同部分分开,使用空行,会影响代码的可读性,根据水平缩进情况来解读代码,不关心垂直间距

4.6.5 其他格式设置指南

PEP 8 – Style Guide for Python Code | peps.python.org

第五章 if语句

5.1 简单示例

  1. cars = ['audi','bmw','subaru','toyota']
  2. for car in cars:
  3. if car == 'bmw': #条件语句,只有宝马首字母大写打印,其他均小写打印
  4. print(car.upper())
  5. else:
  6. print(car.title())

输出结果:

Audi
BMW
Subaru
Toyota

5.2 条件测试

每条if语句的核心都是一个值为true或者false的表达式——条件测试

条件测试的值为TRUE—执行紧跟在if语句后的代码

条件测试的值为FALSE—忽略这些代码

5.2.1 检查是否相等

  1. car = 'bmw'
  2. print(car == 'bmw')

输出结果:True

  1. car = 'Audi'
  2. print(car == 'bmw')

输出结果:False

5.2.2 检查是否相等时不考虑大小写

检查是否相等时,是区分大小写的

  1. car = 'Bmw'
  2. print(car == 'bmw')

输出False

  1. car = 'Bmw'
  2. print(car.lower() == 'bmw')

输出True

5.2.3 检查是否不相等

结合使用惊叹号和等号(!=)

  1. requested_topping = "mushrooms"
  2. if requested_topping != 'anchovies' :
  3. print("Hold the anchovies")

输出Hold the anchovies

5.2.4 比较数字

  1. age = 18
  2. print(age == 18)

输出ture

还可以检查两个数字是否不等:

  1. answer = 17
  2. if answer != 42:
  3. print("That is not the correct answer.")

输出That is not the correct answer.

条件语句中可包含各种数学比较,如大于,小于等于、大于、大于等于

  1. age = 19
  2. print(age < 21)
  3. print(age <= 21)
  4. print(age> 21)
  5. print(age >= 21)

输出

True
True
False
False

5.2.5 检查多个条件

1.使用and检查多个条件

要检查两个条件都为true,使用关键字and:每个测试都通过—True,如果至少有一个测试没有通过,整个表达式就为False

  1. age_0 = 22
  2. age_1 = 18
  3. print(age_0 >= 21 and age_1 >=21)
  4. age_1 = 22
  5. print(age_0 >= 21 and age_1 >=21)

输出

False
True

2.使用or检查多个条件

至少有一个条件满足,就能通过整个测试。仅当两个测试都没通过时,才为false

  1. age_0 = 22
  2. age_1 = 18
  3. print(age_0 >= 21 or age_1 >=21)
  4. age_0 = 18
  5. print(age_0 >= 21 or age_1 >=21)

输出

True
False

5.2.6 检查特定值是否包含在列表中

判断特定的值是否已包含在列表中,使用关键字in

  1. requested_topping = ['mushrooms','onions','pineapple']
  2. print('mushrooms' in requested_topping)
  3. print('pepperoni' in requested_topping)

输出结果

True
False

5.2.7 检查特定值是否不包含在列表中

确定特定的值未包含在列表中,使用关键字not in

  1. banned_users = ['andrew','carolina','david']
  2. user = 'marie'
  3. if user not in banned_users:#如果user 的值未包含在列表banned_users 中,Python将返回True ,进而执行缩进的代码行。
  4. print(user.title() + ",you canpost a response if you want.")

用户’marie’ 未包含在列表banned_users 中,因此她将看到一条邀请她发表评论的消息

输出结果

Marie, you can post a response if you wish.

5.2.8 布尔表达式

  1. game_active = True
  2. print(game_active)
  3. can_edit = False
  4. print(can_edit)

5.3.1 简单的if语句

  1. age = 19
  2. if age > 18:
  3. print("You are old enough to vote!")

5.3.2 if-else语句

在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作,使用if-else语句

  1. age = 17
  2. if age >= 18:
  3. print("You are old enough to vote!")
  4. print("Have you registered to vote yet?")
  5. else:
  6. print("Sorry, you are too young to vote!")
  7. print("Please refuster to vote a soon as you turn 18!")

执行结果

Sorry, you are too young to vote.

Please register to vote as soon as you turn 18!

5.3.3 if-elif-else语句

检查超过两个的情形,只执行if-elif-slse结构中的一个代码块,依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,将执行紧跟其后的代码,并跳过余下的测试

eg:一个根据年龄段收费的游乐场

  • 4岁以下免费
  • 4~18收5块
  • 18(含)以上收10块
  1. age = 12
  2. if age <4:
  3. print("Your admission cost is free.")
  4. elif age < 18:
  5. print("your admission cost is 5.")
  6. else:
  7. print("your admission cost is 10.")

输出结果

your admission cost is 5.

  1. age = 12
  2. if age < 4:
  3. price = 0#简化版本
  4. elif age < 18:
  5. price =5
  6. else:
  7. price = 10
  8. print("your admission cost is " + str(price) + ".")#记得字符串化price

5.3.4 使用多个elif

eg:要给65上以上的老年人打折

  1. age = 12
  2. if age < 4:
  3. price = 0
  4. elif age < 18:
  5. price = 5
  6. elif age < 65:#检查确定年纪不到65岁后,才设置全票
  7. price = 10
  8. else:
  9. price = 5 #65岁老人半价
  10. print("your admission cost is " + str(price) + ".")

5.3.6 测试多个条件

eg:顾客电了两种配料,就需要确保在其比赛中包含这些配料

  1. requested_toppings = ['mushrooms','extra cheese']#列表包含顾客点的配料
  2. if 'mushrooms' in requested_toppings:
  3. print("Adding mushrooms.") #如果点了蘑菇,就打印一条确认消息
  4. if 'pepperoni' in requested_toppings:
  5. print("Adding pepperoni.")
  6. if 'extra cheese' in requested_toppings:
  7. print("Adding extra cheese.")
  8. print("\nFinished making your pizza!")

不管前一个是否通过,都将进行这个测试,这个程序运行时会进行三个独立的测试。

5.4 使用if语句处理列表

5.4.1 检查特殊元素

eg: 比萨店的青椒用完了

  1. requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
  2. for requested_topping in requested_toppings:
  3. if requested_topping == 'green peppers':
  4. print("Sorry, we are out of green peppers right now.")
  5. else:
  6. print("Adding " + requested_topping + ".")
  7. print("\nFinished making your pizza!")

输出结果

Adding mushrooms.

Sorry, we are out of green peppers right now.

Adding extra cheese.

Finished making your pizza!

5.4.2 确定列表不为空

  1. requested_toppings = []
  2. if requested_toppings:#做简单检查,列表为空时返回False
  3. for requested_topping in requested_toppings:
  4. print("Adding " + requested_topping + ".")
  5. print("\nFinished making your pizza")
  6. else:
  7. print("Are you sure you want a plain pizza?")

输出结果:

Are you sure you want a plain pizza?

5.4.3 使用多个列表

  1. available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']#比萨店供应的配料
  2. requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
  3. #顾客点的配料
  4. for requested_topping in requested_toppings:
  5. if requested_topping in available_toppings:
  6. print("Adding " + requested_topping + ".")
  7. else:
  8. print("Sorry, we dont have" + requested_topping + ".")#没有此种配料就打印出不供应的提示
  9. print("\nFinished making your pizza!")

输出结果:

Adding mushrooms.
Sorry, we dont havefrench fries.
Adding extra cheese.

Finished making your pizza!

5.5 设置if语句的格式

if age < 4比 if age<4好

第六章 字典

6.1 一个简单的字典

  1. alien_0 = {'color' :'green' , 'points':5}
  2. print(alien_0['color'])
  3. print(alien_0['points'])

字典alien_0存储了外星人的颜色和点数

输出结果

green
5

6.2 使用字典

字典是一系列键—值对应

字典用放在花括号{ }中的一系列键—值表示

  1. alien_0 = {'color' :'green' }

只存储了一想有关alien_0的信息,’color是一个键’,与之相关联的值为‘green’

6.2.1 访问字典中的值

可依此制定字典名和放在方括号内的键

  1. alien_0 = {'color' :'green' }
  2. print(alien_0['color'])

输出结果:

green

  1. alien_0 = {'color' :'green' , 'points':5}
  2. new_points = alien_0['color']
  3. print("You just earned " + str(new_points) + "points!")

输出结果:

You just earned 5 points!

6.2.2 添加键—值对

字典是一种动态结构,可随时在其中添加键—值对

  1. alien_0 = {'color' :'green' , 'points':5}
  2. print(alien_0)
  3. alien_0['x_position'] = 0 #新增键—值对,其中的键为'x_position',值为0
  4. alien_0['y_position'] = 25
  5. print(alien_0)

输出结果

{‘color’: ‘green’, ‘points’: 5}

{‘color’: ‘green’, ‘points’: 5, ‘y_position’: 25, ‘x_position’: 0}

6.2.3 先创建一个空字典

  1. alien_0 = {}
  2. alien_0['color'] = 'green'
  3. alien_0['points'] = 5
  4. print(alien_0)

创建空字典然后往里面加键与值

输出结果

{‘color’: ‘green’, ‘points’: 5}

6.2.4 修改字典中的值

依次指定字典名、用方括号括起的键以及与该键相关联的新值

  1. alien_0 = {'color':'green'}
  2. print("The alien is " + alien_0['color'] + ".")
  3. alien_0['color'] = 'yellow'#修改值
  4. print("The alien is now " + alien_0['color'] + ".")

输出结果:

The alien is green.

The alien is now yellow.

eg:对一个能够以不同速度移动的外星人位置进行跟踪 存储该外星人的当前速度,据此确定该外星人将向右移动多远

  1. alien_0 = {'x_position':0, 'y_position':25 ,'speed':'medium'}
  2. print("original x-position: " + str(alien_0 ['x_position']))
  3. #向右移动外星人
  4. #根据外星人当前速度决定将其移动多远
  5. if alien_0['speed'] == 'slow':
  6. x_increment = 1
  7. elif alien_0['speed'] == 'medium':
  8. x_increment = 2
  9. else:
  10. # 这个外星人的移动速度一定很快
  11. x_increment = 3
  12. #新位置等于老位置加上增量
  13. alien_0['x_position'] = alien_0['x_position'] + x_increment
  14. print("new x-position: " + str(alien_0['x_position']) )

输出结果

original x-position: 0
new x-position: 2

6.2.5 删除键-值对

对于字典不需要的信息,使用del语句删除

必须指定字典名和要删除的键

eg:从alien_0中删除键’position’及其值:

  1. alien_0 = {'color': 'green','points':5}
  2. print(alien_0)
  3. del alien_0['points']
  4. print(alien_0)

输出结果

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}

6.2.6 由类似对象组成的字典

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python'
  6. }
  7. print("Sarah's favorite language is " +
  8. favorite_languages['sarah'].title() +
  9. ".")

输出结果

Sarah’s favorite language is C.

6.3 遍历字典

6.3.1 遍历所有的键-值对

写法:for key,value in user_0.items()

  1. user_0 = {
  2. 'username' : 'efermi',
  3. 'first' : 'enrico',
  4. 'last' : 'fermi',
  5. }
  6. for key,value in user_0.items():#声明两个变量存储键、值
  7. print("\nKey: " + key)
  8. print("\nValue: " + value)

输出结果:

Key: last

Value: fermi

Key: first

Value: enrico

Key: username

Value: efermi

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. for name , language in favorite_languages.items():
  8. print(name.title() + "‘s favorite language is " +
  9. language.title() + ".")

输出结果:

Jen’s favorite language is Python.

Sarah’s favorite language is C.

Phil’s favorite language is Python.

Edward’s favorite language is Ruby.

6.3.2 遍历字典中的所有键

注意是用 for key in 字典.keys()

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. for name in favorite_languages.keys():#提取字典favorite_language中的所有键,存储在name
  8. print(name.title())

输出结果

Jen
Sarah
Edward
Phil

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. friends = ['phil' , 'sarah'] #创建列表,包含我们要通过打印消息,指出其喜欢的语言的朋友
  8. for name in favorite_languages.keys():
  9. print(name.title())
  10. if name in friends: #检查当前名字是否存在列表friends中
  11. print(" Hi " + name.title()+
  12. ", I see your favorite language is " +
  13. favorite_languages[name].title() + "!")#为访问喜欢的语言,使用字典名,并将变量name的当前值作为键

6.3.3 按顺序遍历字典中的所有键

可使用函数sorted()来获得按特定顺序排列的键列表的副本:

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. for name in sorted(favorite_languages.keys()):
  8. print(name.title() + ", thank you for taking the poll.")

sorted()列出来字典中的所用键,并在遍历前对这个列表进行排序

输出结果

Edward, thank you for taking the poll.

Jen, thank you for taking the poll.

Phil, thank you for taking the poll.

Sarah, thank you for taking the poll.

6.3.4 遍历字典中的所有值

使用方法values()

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. print("The following languages have been mentioned:")
  8. for language in favorite_languages.values():
  9. print(language.title())

输出结果

The following languages have been mentioned:

Python

C

Python

Ruby

剔除重复项python,使用set集合

  1. favorite_languages = {
  2. 'jen':'python',
  3. 'sarah':'c',
  4. 'edward':'ruby',
  5. 'phil':'python',
  6. }
  7. print("The following languages have been mentioned:")
  8. for language in set(favorite_languages.values()):
  9. print(language.title())

输出结果

The following languages have been mentioned:

Python

C
Ruby

6.4 嵌套

将字典存储在列表中/将列表作为值存储在字典中,称为嵌套

6.4.1 字典列表

  1. alien_0 = {'color':'green' , 'points':5}
  2. alien_1 = {'color':'yellow','points':10}
  3. alien_2 = {'color' : 'red','points':15}#创建三个字典装3个外星人
  4. aliens = [alien_0, alien_1 ,alien_2]#把字典都放到aliens列表中
  5. for alien in aliens:#遍历整个列表,打印出
  6. print(alien)
  1. aliens = []
  2. for alien_number in range(30):
  3. new_alien = {'color':'green', 'points':5, 'speed':'slow'}
  4. aliens.append(new_alien)#创建30个绿色儿的外星人
  5. for alien in aliens[:5]:#显示前五个外星人
  6. print(alien)
  7. print("...")
  8. print("Total number of aliens: " + str(len(aliens)) )

输出结果

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

Total number of aliens: 30

  1. aliens = []
  2. for alien_number in range(30):
  3. new_alien = {'color':'green', 'points':5, 'speed':'slow'}
  4. aliens.append(new_alien)#创建30个绿色儿的外星人
  5. for alien in aliens[0:3]:#修改前三个外星人变成黄色儿、速度为中等,值为10
  6. if alien['color'] == 'green':
  7. alien['color'] = 'yellow'
  8. alien['speed'] = 'medium'
  9. alien['points'] =10
  10. for alien in aliens[0:5]:
  11. print(alien)
  12. print("...")

输出结果

{‘speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’: 10}

{‘speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’: 10}

{‘speed’: ‘medium’, ‘color’: ‘yellow’, ‘points’: 10}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

{‘speed’: ‘slow’, ‘color’: ‘green’, ‘points’: 5}

6.4.2 在字典中存储列表

  1. #存储所点比萨的信息
  2. pizza = {
  3. 'crust':'thick',
  4. 'toppings':['mushrooms','extra cheese'],#字典中存储列表
  5. }
  6. #概述所点的比萨
  7. print("You ordered a " + pizza['crust'] + "-crust pizza" +
  8. "with the following toppings:")
  9. for topping in pizza['toppings']:
  10. print("\t" + topping)

输出结果

You ordered a thick-crust pizzawith the following toppings:
mushrooms
extra cheese

  1. favorite_languages = { #与每个名字关联的值都是一个列表
  2. 'jen' :['python','ruby'],
  3. 'sarah':['c'],
  4. 'edward':['ruby','go'],
  5. 'phil':['python','haskell']
  6. }
  7. for name ,languages in favorite_languages.items():#使用变量languages来依次存储字典中的每个值
  8. print("\n" + name.title() + "'s favorite languages are :")
  9. for language in languages:
  10. print("\t" + language.title())

输出结果

Jen’s favorite languages are :
Python
Ruby

Sarah’s favorite languages are :
C

Edward’s favorite languages are :
Ruby
Go

Phil’s favorite languages are :
Python
Haskell

6.4.3 在字典中存储字典

eg:对于每位用户,都存储三项信息:名、姓、居住地;为访问这些信息,遍历所有的用户名,并访问每个与用户名相关联的信息字典:

  1. users = {
  2. 'aeinstein': {
  3. 'first': 'albert',
  4. 'last': 'einstein',
  5. 'location': 'princeton',
  6. },
  7. 'mcurie': {
  8. 'first': 'marie',
  9. 'last': 'curie',
  10. 'location': 'paris'
  11. },
  12. }
  13. for username, user_info in users.items():#包括两个键,用户名'aeinstein''mcurie'
  14. print("\nUsername: " + username)
  15. full_name = user_info['first'] + " " + user_info['last']#访问内部字典
  16. location = user_info['location']
  17. print("\tFull name: " + full_name.title())
  18. print("\tLocation: " + location.title())

第七章 用户输入和while循环

7.1 函数input()的工作原理

eg:让用户输入一些文本,在将这些文本呈现给用户

  1. message = input("Tell me something ,and I will repeat it back to you: ")
  2. print(message)

输出结果

Tell me something ,and I will repeat it back to you: a #输入a后按回车
a#输出a

7.1.1 编写清晰的程序

每当你使用函数input() 时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息—指出用户该输入任何信息的提示都行

  1. name = input("Please enter your name: ")
  2. print("Hello, " + name + "!")

输出结果

Please enter your name: echo
Hello, echo!

  1. prompt = "If you tell us who you are, we can personalize the messages you see."
  2. prompt +="\nWhat is your first name?"
  3. #运算符——=在存储在prompt中的字符串末尾附加一个字符串
  4. name = input(prompt)
  5. print("\nHello, " + name + "!")

输出结果

If you tell us who you are, we can personalize the messages you see.
What is your first name?Echo

Hello, Echo

7.1.2 使用int()来获取数值输入

使用函数input()时,用户输入的内容被理解为字符串

为解决将输入用于数值比较时,可使用函数int()进行字符转换

eg:身高满足多少可以开车

  1. heigh = input("How tall are you , in inches? ")
  2. heigh = int(heigh)#数值转换
  3. if heigh >= 36:
  4. print("\nYou're tall enough to ride!")
  5. else:
  6. print("\nYou'll be able to ride when you're a little older")

7.1.3 求模运算符

%两数相除求余数

  1. print(4 % 3)#两数相除返回余数——1
  2. print(5 % 3)#——2
  3. print(6 % 3)#——0

可以被整除时余数为0(判断奇偶数):

  1. number = input("Enter a number, and I’ll tell you if it's even or odd:")
  2. number = int(number)
  3. if number % 2 == 0:
  4. print("\nThe number " + str(number) + "is even.")
  5. else:
  6. print("\nThe number " + str(number) + " is odd.")

7.2 while循环简介

7.2.1使用while 循环

while循环不断的运行,直到指定的条件不满足为止

  1. current_number = 1
  2. while current_number <=5:#只要满足current_number <=5 Python就接着运行,不断输出且+1
  3. print(current_number)
  4. current_number += 1

输出结果

1

2

3

4

5

7.2.2 让用户选择何时退出

eg:只要用户输入的不是quit,就接着运行

  1. prompt = "\nTell me something, and I will repeat it back to you:"
  2. prompt += "\nEnter 'quit' to end the program."
  3. message = ""
  4. while message != 'quit':
  5. message = input(prompt)
  6. if message != 'quit':
  7. print(message)

7.2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可以定义一个变量—标志

  1. prompt = "\nTell me something, and I will repeat it back to you:"
  2. prompt += "\nEnter 'quit' to end the program."
  3. active = True #设置为true,让程序最初处于活动状态(简化while语句,不用做任何比较)
  4. while active:
  5. message = input(prompt)
  6. if message == 'quit':
  7. active = False
  8. else:
  9. print(message)

7.2.4 使用break退出循环

立即退出while循环,不再运行循环中余下的代码

  1. prompt = "\nPlease enter the name of a city you have visited:"
  2. prompt += "\n(Enter 'quit' when you are finished.)"
  3. while True:#以while true打头的循环将不断运行,直到遇到break语句
  4. city = input(prompt)
  5. if city == 'quit':
  6. break
  7. else:
  8. print("I'd love to go to " + city.title() + "!")

7.2.5 在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用coutinue语句

eg: 来看一个数从1到10,但只打印其中偶数的循环

  1. curren_nmber = 0
  2. while curren_nmber < 10:
  3. curren_nmber += 1
  4. if curren_nmber % 2 == 0:
  5. continue
  6. print(curren_nmber)

输出结果

1
3
5
7
9

7.2.6 避免无限循环

每个while循环都必须有停止运行的途径

陷入无限循环,按ctrl+c

7.3 使用while循环来处理列表和字典

记录大量的用户和信息,需要在while循环中使用列表和字典

for循环遍历列表时不应修改列表,要在遍历列表同时对其进行修改,可以使用while循环。

通过将while循环同列表和字典结合使用,可收集、存储并组织大量输入

7.3.1 在列表之间移动元素

eg:有一个列表,其中包含新注但还未验证的网站用户,验证这些用户以后,如何将其移动到另一个已验证用户列表中?

方法1:使用一个while循环,验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个以验证用户列表中:

  1. # 首先创建一个待验证用户列表
  2. # 和一个用于存储已验证用户的空列表
  3. unconfirmed_users = ['alice','brain','candace']
  4. confirmed_users = []
  5. #验证每个用户,直到没有未验证用户为止
  6. #将每个经过验证的列表都移动到已验证用户列表中
  7. while unconfirmed_users:
  8. current_user = unconfirmed_users.pop()
  9. print("Verifying user: " + current_user.title())
  10. confirmed_users.append(current_user)
  11. #显示所有已验证的用户
  12. print("\nThe following users have been confirmed:")
  13. for confirmed_user in confirmed_users:
  14. print(confirmed_user.title())

输出结果

Verifying user: Candace
Verifying user: Brain
Verifying user: Alice

The following users have been confirmed:
Candace
Brain
Alice

7.3.2 删除包含特定值的所有列表元素

eg:有一个宠物列表,包含多个值为’cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表不再包含值‘cat’

  1. pets = ['dog' , 'cat' , 'goldfish' , 'cat' , 'rabbit' , 'cat']
  2. print(pets)
  3. while 'cat' in pets:#进入循环中,删除第一个'cat'并返回到while代码行,然后发现'cat'还包含在列表中,再次进入循环。不断删除'cat'直到这个值不再包含在列表中,然后退出循环并再次打印列表
  4. pets.remove('cat')
  5. print(pets)

[‘dog’, ‘cat’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
[‘dog’, ‘goldfish’, ‘rabbit’]

7.3.3 使用用户输入来填充字典

可使用while循环体使用户输入任意数量的信息。

eg:创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答

将收集的数据存储在一个字典中,一遍将回答同被调查者关联起来

  1. responses = {}
  2. #设置一个标志,指出调查是否继续
  3. polling_active = True
  4. while polling_active:#提示输入被调查者的名字和回答
  5. name = input("\nWhat is your name?")
  6. response = input("Which mountain would you like to climb someday?")
  7. responses[name] = response#将答卷存储在字典中
  8. repeat = input("Would you like to let another person respond?(yes/no) ")#看看是否还有人要参与调查
  9. if repeat == 'no':
  10. polling_active = False
  11. #调查结束,显示结果
  12. print("\n---Poll Results ---")
  13. for name, response in responses.items():
  14. print(name + " Would like to climb " + response + ".")

What is your name?Echo
Which mountain would you like to climb someday?Emei Mountain
Would you like to let another person respond?(yes/no) yes

What is your name?Pdan
Which mountain would you like to climb someday?MAOMAO Moumtain
Would you like to let another person respond?(yes/no) no

—-Poll Results —-
Echo Would like to climb Emei Moutain.
Pdan Would like to climb MAOMAO Moutain.

第八章 函数

8.1 定义函数

打印问候语的简单函数:greet_user():

  1. def greet_user():
  2. """显示简单的问候语"""
  3. print("Hello!")
  4. greet_user()

语法: 定义—def+函数名,以冒号结尾

8.1.1 向函数传递信息

  1. def greet_user(username):#在函数内添加值
  2. """显示简单的问候语"""
  3. print("Hello! " + username.title() + "!")
  4. greet_user('jesse')#调用时指定一个值,可将一个名字传递给它

调用时无论传入什么杨的名字,都会生成相应的输出。

8.1.2 实参和形参

在函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息

在代码greet_user(‘jesse’)中,值’jesse’是一个实参——调用函数时传递给函数的信息

调用函数时,将要使用的信息放在括号内,实参’jesse’传递给了函数greet_user(),其值被存储到形参username中

8.2 传递实参

函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参

向函数传递实参的方式很多,

  • 可使用位置实参,要求实参的顺序与形参的顺序相同,
  • 也可使用关键字实参,其中每个实参都由变量名和值组成
  • 还可使用列表和字典。

8.2.1 位置实参

eg:需要一种宠物类型和一个名字

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name + "." )
  5. describe_pet('hamsrer','harry')

I have a hamsrer.
My hamsrer’s name is harry.

1.调用函数多次

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + "." )
  5. describe_pet('hamsrer','harry')
  6. describe_pet('dog','willie')

I have a hamsrer.
My hamsrer’s name is Harry.

I have a dog.
My dog’s name is Willie.

2.位置实参的顺序很重要

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + "." )
  5. describe_pet('harry','hamsrer')#实参的顺序写反了会导致调用后的输出有问题

I have a harry.

My harry’s name is Hamster.

8.2.2 关键字实参

关键字实参是传递给函数的名—值对,无需考虑函数调用中的实参顺序,清楚地指出了函数调用中各个值的用途

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + "." )
  5. describe_pet(animal_type='hamster',pet_name='harry')

8.2.3 默认值

给每个形参指定默认值,若未提供实参时将使用形参的默认值

给形参指定默认值后,可在函数调用中省略对应的实参。

  1. def describe_pet(pet_name,animal_type='dog'):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + "." )
  5. describe_pet(pet_name='harry')

注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参

  1. describe_pet(pet_name='harry', animal_type='hamster')

若提供了实参,默认形参值将会被忽略

8.2.4 等效的函数调用

  1. # 一条名为Willie的小狗
  2. describe_pet('willie')
  3. describe_pet(pet_name='willie')
  4. # 一只名为Harry的仓鼠
  5. describe_pet('harry', 'hamster')
  6. describe_pet(pet_name='harry', animal_type='hamster') describe_pet(animal_type='hamster', pet_name='harry')

8.2.5 避免实参错误

如果调用函数describe_pet()时没有指定任何实参

  1. def describe_pet(pet_name,animal_type='dog'):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + "." )
  5. describe_pet()#没有指定任何实参 将会报错

8.3 返回值

函数处理一些数据,并返回一个或一组值

返回的值称为返回值

可使用return语句将值返回到调用函数的代码行

8.3.1 返回简单值

  1. def get_formatted_name(first_name, last_name):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + last_name#将姓名合二为一,存储在full_name变量中
  4. return full_name.title()#将full_name的值转换为首字母大写格式
  5. musician = get_formatted_name('jimi' ,'hendrix')#将返回值存储在了变量musician
  6. print(musician)

Jimi Hendrix

8.3.2 让实参变成可选的

eg:扩展参数get_formatted_name(),使其还处理中间名

  1. def get_formatted_name(first_name, middle_name, last_name):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + middle_name + ' ' + last_name
  4. return full_name.title()
  5. musician = get_formatted_name('jimi' , 'lee', 'hendrix')
  6. print(musician)

Jimi Lee Hendrix

  • 只要同时提供名、中间名和姓,这个函数就能正确运行
  • 根据这三部分创建一个字符串,在适当的地方加上空格,并将结果转换为首字母大写格式

eg:当一个人不存在中间名,但如果调用上面的函数时只提供了名和姓,将不能正确的运行,让中间名变成可选的,可给实参middle_name 指定一个默认值—空字符串,并将其转移到列表末尾:

  • 中间名可选,因此在函数定义中最后列出该形参,并将其默认值设置为空字符串
  1. def get_formatted_name(first_name, last_name, middle_name=''):
  2. """返回整洁的姓名"""
  3. if middle_name:#非空字符会被解读为True,提供了中间名,middle_name将为True
  4. full_name = first_name + ' ' + middle_name + ' ' + last_name
  5. else:
  6. full_name = first_name + ' ' + last_name
  7. return full_name.title()
  8. musician = get_formatted_name('jimi', 'hendrix')
  9. print(musician)
  10. musician = get_formatted_name('jimi', 'lee', 'hendrix')
  11. print(musician)

Jimi Hendrix
Jimi Hendrix Lee

8.3 返回字典

函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构

eg:函数build_person()接受名和姓,将这些值封装到字典中,存储first_name的值时,使用的键为’first’,而存储last_name的值时,使用的键为’last’,最后,返回表示人的整个字典

  1. def build_person(first_name, last_name):
  2. """返回一个字典,其中包含有关一个人的信息"""
  3. person = {'first':first_name, 'last':last_name}
  4. return person
  5. musician = build_person('jimi', 'hendrix')
  6. print(musician)
  7. print(build_person('a','b'))

{‘first’: ‘jimi’, ‘last’: ‘hendrix’}
{‘first’: ‘a’, ‘last’: ‘b’}

eg:可以轻松扩展这个函数,使其接受可选值,如中间名、年龄、职业等,下面的修改让你还能存储年龄

  1. def build_person(first_name, last_name, age=''):#新增可选形参age,默认值设置为空字符串
  2. """返回一个字典,其中包含有关一个人的信息"""
  3. person = {'first':first_name, 'last':last_name}
  4. if age:#如果函数调用中包含age的值,这个值将存储到字典中
  5. person['age'] = age
  6. return person
  7. musician = build_person('jimi', 'hendrix', age=27)
  8. print(musician)

8.3.4 结合使用函数和while循环

结合使用函数get_formatted_name()和while循环,以更正规的方式问候用户。

  1. def get_formatted_name(first_name, last_name,):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + last_name
  4. return full_name.title()
  5. while True:
  6. print("\nPlease tell me your name:")
  7. print("(enter 'q' at any time to quit")
  8. f_name = input("First name:")
  9. if f_name == 'q': #退出条件防止无限循环
  10. break
  11. l_name = input("Last_name:")
  12. if l_name == 'q':
  13. break
  14. formatted_name = get_formatted_name(f_name, l_name)
  15. print("\nHello, " + formatted_name + "!")

Please tell me your name:
enter ‘q’ at any time to quit
First name:a
Last_name:b

Hello, A B!

First name:a
Last_name:q

Process finished with exit code 0

8.4 传递列表

向函数传递列表,列表包含的可能是名字、数字或更复杂的对象(如字典)

使用函数可以提高处理列表的效率。

eg:有一个用户列表,要问候其中的每位用户

  1. def greet_users(names):#定义成接受一个名字列表,并将其存储在形参names
  2. """向列表中的每位用户都发出简单的问候"""
  3. for name in names:
  4. msg = "Hello, " + name.title() + "!"
  5. print(msg)
  6. usernames = ['hannah', 'ty', 'margot']#定义一个用户列表
  7. greet_users(usernames)#调用greet_users()并将这个列表传递给它

Hello, Hannah!
Hello, Ty!
Hello, Margot!

8.4.1 在函数中修改列表

任何修改都是永久性的

eg:一家为用户提交设计制作3D打印模型的公司。需要打印的设计存储在一个列表中,打印后移到另一个列表中

  1. # 首先创建一个列表,其中包含一些要打印的设计
  2. unprinted_designs = ['iphone case','robot pendant','dodecahedron']
  3. completed_models = []
  4. #模拟打印每个设计,直到没有未打印的设计为止
  5. #打印每个设计后,都将其移到列表completed_models中
  6. while unprinted_designs:
  7. curren_design = unprinted_designs.pop()
  8. #模拟根据设计制作3D打印模型的过程
  9. print("Printing model:" + curren_design)
  10. completed_models.append(curren_design)
  11. #显示所有打印好的模型
  12. print("\nThe following models have been printed:")
  13. for completed_model in completed_models:
  14. print(completed_model)

Printing model:dodecahedron
Printing model:robot pendant
Printing model:iphone case

效率更高的来处理这个函数

  1. def print_moderls(unprinted_designs, completed_models):
  2. """
  3. 模拟打印每个设计,直到没有未打印的设计为止
  4. 打印每个设计后,都将其移到列表completed_models中
  5. """
  6. while unprinted_designs:
  7. curren_design = unprinted_designs.pop()
  8. #模拟根据设计制作3D打印模型的过程
  9. print("Printing model:" + curren_design)
  10. completed_models.append(curren_design)
  11. def show_completed_models(completed_models):#定义了函数show_completed_model(),包含一个形参:打印好的模型列表,给定这个列表,函数show_completed_models()显示打印出来的每个模型的名字
  12. """显示所有打印好的模型"""
  13. print("\nThe following models have been printed:")
  14. for completed_model in completed_models:
  15. print(completed_model)
  16. unprinted_designs = ['iphone case' ,'robot pendant' ,'dodecahedron']
  17. completed_models = []
  18. print_moderls(unprinted_designs, completed_models)
  19. show_completed_models(completed_models)

8.2.4 禁止函数修改列表

eg: 有一个未打印的设计列表,编写了一个将这些设计移到打印好的模型列表中的函数,

即时打印所有设计后,也要保留原来的未打印的设计列表,以便备案。

为解决这个问题,可向函数传递列表的副本而不是原件

要将列表的副本传递给函数,可像下面这样做:

  1. function_name(list_name[:])

切片表示法[:]创建列表的副本,如果不想清空未打印的设计列表,可像下面这样调用print_models():

  1. print_models(inprinted_designs[:],completed_models)

8.5 传递任意数量的实参

预先不知道函数需要接收多少个实参,好在Python允许函数从调用语句中收集任意数量的实参

eg:制作比萨的函数,它需要接受很多配料,但你无法预先确定顾客要多少种配料

下面的函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中:

  1. def make_pizza(*toppings):
  2. """打印顾客点的所有配料"""
  3. print(toppings)
  4. make_pizza('pepperoni')
  5. make_pizza('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings中的星号让py创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组内

函数体内的print语句通过生成输出来证明python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用

(‘pepperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

现在,我们可以将这条print语句替换成一个循环,对配料列表进行遍历,并对顾客点的比萨进行描述:

  1. def make_pizza(*toppings):
  2. """打印顾客点的所有配料"""
  3. print("\nMaking a pizza with the following toppings:")
  4. for topping in toppings:
  5. print("- " + topping)
  6. make_pizza('pepperoni')
  7. make_pizza('mushrooms', 'green peppers', 'extra cheese')

不管收到的是一个值还是三个值,这个函数都能妥善地处理:

Making a pizza with the following toppings:

  • pepperoni

Making a pizza with the following toppings:

  • mushrooms
  • green peppers
  • extra cheese

不管函数收到的实参多少,这种语法都管用。

8.5.1 结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。先匹配位置实参和关键字实参,在将于下的是实参收集到最后一个形参中。

eg:前面的函数还需要一个表示比萨尺寸的实参,必须将该形参防止形参*toppings的后面:

  1. def make_pizza(size,*toppings):#将收到的第一个值存储在形参size中,并将其他的所有值都存储在元组toppings中。
  2. """打印顾客点的所有配料"""
  3. print("\nMaking a " + str(size) +
  4. "-inch pizza with the following toppings:")
  5. for topping in toppings:
  6. print("- " + topping)
  7. make_pizza(16,'pepperoni')
  8. make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:

  • pepperoni

Making a 12-inch pizza with the following toppings:

  • mushrooms
  • green peppers
  • extra cheese

8.5.2 使用任意数量的关键字实参

将函数编写成能够接受任意数量的键-值对-调用语句提供了多少就接受多少。

在下面的示例中,函数build_profile()接受名和姓,同时还接受任意数量的关键字实参:

  1. def build_profile(first, last, **user_info):
  2. """创建一个字典,其中包含我们知道的有关用户的一切"""
  3. profile = {}
  4. profile['first_name'] = first
  5. profile['last_name'] = last
  6. for key,value in user_info.items():
  7. profile[key] = value
  8. return profile
  9. user_profile = build_profile('albert','einstein',
  10. lacation='princeton',
  11. field='physics')
  12. print(user_profile)

{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’,

‘lacation’: ‘princeton’, ‘field’: ‘physics’}

8.6 将函数存储在模块中

函数的优点之一:使用它们可将代码与主程序分离

通过给函数指定描述性名词,可增加主程序易读性,再将模块导入到主程序中

import语句允许在当前运行的程序文件中使用模块中的代码

将函数存储在被称为模块的独立文件中,再将模块导入到主程序中,可隐藏程序代码的细节

8.6.1 导入整个模块

要让函数是可导入的,需先创建模块

模块是扩展名为.py的文件,包含要导入到程序中的代码

创建一个包含函数make_pizza()的模块,为此将pizza.py中除了函数make_pizza()之外的其他代码都删除

  1. def make_pizza(size,*toppings):
  2. """概述要制作的比萨"""
  3. print("\nMaking a " + str(size) +
  4. "-inch pizza with the folloing toppings:")
  5. for topping in toppings:
  6. print("- " + topping)

接下来,在此目录中创建另一个名为making_pizzas.py的文件,这个文件倒入刚创建的模块,再调用make_pizza()两次:

  1. import pizza#只需要编写一条import语句并在其中指定模块名,就可在程序中使用该模块中的所有函数
  2. pizza.make_pizza(16,'pepperoni')
  3. pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')

Making a 12-inch pizza with the folloing toppings:

  • mushrooms
  • green peppers
  • extra cheese

如果使用这种import语句导入了名为module_name.py的整个模块,就可使用下面的语法来使用其中任何一个函数:

  1. module_name.function_name()

8.6.2 导入特定的函数

语法:

  1. from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数

  1. from module_name import function_0, function_1,function_2

对于前面的making_pizzas.py示例,如果只想导入要使用的函数,代码将类似于下面

  1. from pizza import make_pizza
  2. make_pizza(16,'pepperoni')
  3. make_pizza(12,'mushromms','green peppers','extra cheese')

若使用这种语法,调用函数时就无需使用句点。由于我们在import语句中显式地导入了函数make_pizza(),因此调用它时只需指定其名称

8.6.3 使用as给函数指定别名

如果要导入的函数名称可能与程序中现有的名称冲突,或者函数的名称过长,可指定简短而独一无二的别名——函数的另一个名称,类似于外号

指定别名的通用语法:

  1. from module_name import function_name as fn

下面给函数make_pizza()制定了别名mp()。这是在import语句中使用make_pizza as bmp实现的。

关键字as将函数重命名为提供的别名:

  1. from pizza import make_pizza as mp
  2. mp(16,'pepperoni')
  3. mp(12,'mushrooms','green peppers','extra cheese')

8.6.4 使用as给模块指定别名

给模块指定别名。通过给模块指定简短的别名(如给模块pizza指定别名),能够更轻松地调用模块中的函数。相比pizza.make_pizza(),p.make_pizza()更为整洁:

  1. import pizza as p
  2. p.make_pizza(16,'pepperoni')
  3. p.make_pizza(12,'mushrooms','green peppers','extra cheese')

给模块pizza 指定了别名p,但该模块中所有函数的名称都没有变。调用函数make_pizza()时,可编写代码p.make_pizza()而不是pizza.make_pizza(),这样不仅能使代码更简洁,还可以让你不再关注模块名,而专注于描述性的函数名

这些函数名明确地指出了函数的功能,对理解代码而言,它们比模块名更重要

给模块指定别名的通用语法如下:

  1. import module_name as mn

8.6.5 导入模块中的所有函数

使用星号(*)运算符可让python导入模块中的所有函数:

  1. from pizza import *
  2. make_pizza(16, 'pepperoni')
  3. make_pizza(12, 'mushrooms','green peppers','extra cheese')

Making a 16-inch pizza with the following toppings:

  • pepperoni

Making a 12-inch pizza with the following toppings:

  • mushrooms
  • green peppers
  • extra cheese

import中的*让python将模块pizza中的每个函数都复制到这个程序文件中

语法

  1. from module_name import *

8.7 函数编写指南

给形参指定默认值时,等号两边不要有空格

  1. def function_name(parameter_0, parameter_1='default value')

对于函数调用中的关键字实参,也应遵守这种约定

  1. function_name(value_0, parameter_1='value')

第九章 类

9.1 创建和使用类

9.1.1 创建Dog类

根据Dog类创建的每个实例都将存储名字和年龄

赋予每条小狗蹲下(sit()) 和打滚(roll_over())的能力:

  1. class Dog():#1
  2. """一次模拟小狗的简单尝试"""
  3. def __init__(self, name, age):
  4. """初始化属性name和age"""
  5. self.name = name
  6. self.age = age
  7. def sit(self):
  8. """模拟小狗被命令时蹲下"""
  9. print(self.name.title() + " is now sitting")
  10. def roll_over(self):
  11. """模拟小狗被命令时打滚"""
  12. print(self.name.title() + "rolled over")

1 定义了一个名为Dog的类。在Python中,首字母大写的名称指的是类。类定义中的括号为空—要从空白创建这个类

1.方法init()

类中的函数称为—方法

包含了三个形参:self、name、age