Python学习笔记

Python学习笔记

写在最前面

对于测试人员来说熟悉一门语言是最基本的要求,而Python以其高简洁效率、以及良好的拓展性成为众多小伙伴的不二选择。
这篇文章主要时为了记录我学习过程中的笔记和一些问题,方便以后查阅。
我选择的书是埃里克·马瑟斯的《Python编程:从入门到实践》,本书是一本针对所有层次的Python读者而作的入门书籍,全书分为两部分:第一部分介绍Python编程所必须了的基本概念,包括Python库和工具,以及列表、字典、if语句、类、文件与异常、代码测试等内容;第二部分将理论付诸实践,讲解如何开发三个项目。

搭建编程环境

Python2 和 Python3

当前有两个不同的Python版本:Python2和较新的Python3。
如果你的系统安装的是Python3,有些使用Python2编写的代码可能无法正确的运行。Pyhton3是趋势,所以我们优先安装Python3使用。

在不同的操作系统中搭建Pyhton环境

Python是一种跨平台的编程语言,这意味着它能够运行在所有主要的操作系统中。

Linux 系统

在大多数Linux计算机中都默认安装了Python,因此我们只需要检查一下Pyhton的版本是否是我们所需要的:

[www@childNode-3 ~]$ python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

退出Python并返回到终端窗口:WIN+D或者执行命令exit()。

Windows 系统

首先,检查是否安装了Python
  1. WIN+R打开命令窗口
  2. 输入Python并按Enter
    如果出现了Python提示符(>>>),就说明你的系统安装了Python,否则会看到一条错误消息,指出python是无法识别的命令。
其次,安装Python
  • 确保选中复选框Add Python to PATH
    在这里插入图片描述
打开Python
  • 首先找到了Pyhton文件的路径:D:\04sofaware\python\python3.7.2\setup
    在这里插入图片描述
  • 命令窗口中打开Python终端:

C:\Users\TDH>D:\04sofaware\python\python3.7.2\setup\python3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit
(Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

  • 退出终端:WIN+D或者执行命令exit()
安装文本编辑器

Pyhton的文本编辑器推荐PyCharm。
PyCharm是一款专用的Pyhton编辑器,具有诸多的优势,感兴趣可以安装使用。

变量和简单的数据类型

编辑器运行Python程序的过程说明

print("Hello World!")
Hello World!

解释说明:

运行文件Demo.py时,末尾的.py指出这是一个Python程序,因此编辑器将使用Python解释器来运行它。Python解释器读取整个程序,确定其中每个单词的含义。例如,看到单词print时,解释器就会将括号中的内容打印到屏幕,而不会管括号中的内容是什么。
编写程序时,编辑器会以各种方式突出程序的不同部分。例如,它知道print是一个函数的名称,因此将其显示为蓝色;它知道“Hello Python world!”不是Python代码,因此将其显示为橙色。这种功能称为语法突出,在你刚开始编写程序时很有帮助。

变量

在程序中可随时修改变量的值,而Python将始终记录变量的最新值。

变量的命名规则

  • 变量名只能包含字母、数字和下划线变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
  • 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
  • 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词
  • 变量名应既简短又具有描述性,例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好
  • 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0
  • 随着经验的积累和阅读别人的代码,善于创建有意义的变量名
  • 应使用小写的Python变量名,虽然在变量名中使用大写字母虽然不会导致错误

避免引用变量名错误

message = "Hello World"
print(mesage)
Traceback (most recent call last):
  File "D:/MINE/python/new201103/Demo.py", line 2, in <module>
    print(mesage)
NameError: name 'mesage' is not defined

解释说明:

程序存在错误时,Python解释器将竭尽所能地帮助你找出问题所在。
程序无法成功地运行时,解释器会提供一个traceback。traceback是一条记录,指出了解释器尝试运行代码时,在什么地方错误。
解释器指出,文件Demo.py的第2行存在错误;它列出了这行代码,旨在帮助你快速找出错误,它还指出了它发现的是什么样的错误。在这里,解释器发现了一个名称错误,并指出打印的变量mesage未定义:Python无法识别你提供的变量名。
名称错误通常意味着两种情况:要么是使用变量前忘记了给它赋值,要么是输入变量名时拼写不正确。

字符串

字符串就是一系列字符。
在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号:

“This is a string.'This is also a string.'
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."

关于字符串的几个函数

.title()
name = "palien zhang"
print(name.title())
Palien Zhang

解释说明:

title()以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写。

小写的字符串"palien zhang"存储到了变量name中。在print()语句中,方法title()出现在这个变量的后面。方法是Python可对数据执行的操作在name.title()中,name后面的句点(.)让Python对变量name执行方法title()指定的操作。每个方法后面都跟着一对括号,这是因为方法通常需要额外的信息来完成其工作。这种信息是在括号内提供的。函数title()不需要额外的信息,因此它后面的括号是空的。

PyChram有一个功能:按住Ctrl+鼠标点击方法名可以转到对应的函数代码查看
在这里插入图片描述
在这里插入图片描述
可以方便理解。

.upper()

将字符串改为全部大写。

.lower()

将字符串改为全部小写。
存储数据时,方法lower()很有用。
很多时候,你无法依靠用户来提供正确的大小写,因此需要将字符串先转换为小写,再存储它们。

合并(拼接)字符串

Python使用加号(+)来合并(拼接)字符串

first_name = "zhang"
last_name = "palien"
full_name = first_name+" "+last_name
message = "Hello,"+full_name.title()+"!"
print(message)
Hello,Zhang Palien!

空白字符串

空白泛指任何非打印字符,如空格、制表符和换行符。

制表符 \t

要在字符串中添加制表符,可使用字符组合\t.

print("Python")
print("\tPython")
Python
	Python
换行符 \n

要在字符串中添加换行符,可使用字符组合\n.

print("Languages:\nPyhton\njava\nC+")
Languages:
Pyhton
java
C+
结合使用

制表符和换行符可以结合使用.

print("Languages:\n\tPyhton\n\tjava\n\tC+")
Languages:
	Pyhton
	java
	C+
删除空白

对程序员来说,'python’和’python '看起来几乎没什么两样,但对程序来说,它们却是两个不同的字符串

空白很重要,因为你经常需要比较两个字符串是否相同。

Python能够找出字符串多余的空白:开头、末尾、两端

language = "Python "
print("*"+language+"*")
language = language.rstrip()
print("*"+language+"*")
*Python *
*Python* 0

在编程中,经常需要修改变量的值,再将新值存回到原来的变量中。这就是变量的值可能随程序的运行或用户输入数据而发生变化的原因。

剔除字符串开头的空白:lstrip()
同时剔除字符串两端的空白:strip()

在实际程序中,这些剥除函数最常用于在存储用户输入前对其进行清理。

字符串的语法错误

程序中包含非法的Python代码时,就会导致语法错误。
例如,在用单引号括起的字符串中,如果包含撇号,就将导致错误。

message = "One of Python's strengths is its diverse community."
print(message)
message = 'One of Python's strengths is its diverse community.'
print(message)
  File "D:/MINE/python/new201103/Demo.py", line 3
    message = 'One of Python's strengths is its diverse community.'
                             ^
SyntaxError: invalid syntax

编写程序时,编辑器的语法突出功能可帮助你快速找出某些语法错误:
在这里插入图片描述

数字

整数

在Python中,可对整数执行加(+)减(-)乘(*)除(/)乘方(**)括号次序()运算。

import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['D:\\MINE\\python\\new201103', 'D:/MINE/python/new201103'])
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
3+2
5
3-2
1
3*2
6
3/2
1.5
3**2
9
(3+2)*4
20

浮点数

Python将带小数点的数字都称为浮点数
Python会按照通常的方式处理浮点数的计算,需要注意的是,结果包含的小数位数可能是不确定的:

0.2+0.1
0.30000000000000004
3*0.1
0.30000000000000004

数转换为字符串的处理

age = 23
message = "Happy "+age+"rd Birthday!"
print(message)
Traceback (most recent call last):
  File "D:/MINE/python/new201103/Demo.py", line 2, in <module>
    message = "Happy "+age+"rd Birthday!"
TypeError: can only concatenate str (not "int") to str

解释说明:
这是一个类型错误。
Python发现你使用了一个值为整数(int)的变量,但它不知道该如何解读这个值。
Python知道,这个变量表示的可能是数值23,也可能是字符2和3。像上面这样在字符串中使用整数时,需要显式地指出你希望Python将这个整数用作字符串。
为此,可调用函数str(),它让Python将非字符串值表示为字符串:

age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)
Happy 23rd Birthday!

Python2中的数据处理

在Python 2中,整数除法的结果只包含整数部分,小数部分被删除。请注意,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。
若要避免这种情况,务必确保至少有一个操作数为浮点数,这样结果也将为浮点数。

注释

在大多数编程语言中,注释都是一项很有用的功能,注释让你能够使用自然语言在程序中添加说明。
编写注释的主要目的是阐述代码要做什么,以及是如何做的。
养成注释的习惯,因为相比回过头去再添加注释,删除多余的注释要容易得多。
在Python中,注释用井号(#)标识。井号后面的内容都会被Python解释器忽略:

# 向大家问好
print("Hello Everyone!")
Hello Everyone!

关于Python之禅

在开发期间,灵活性是可以接受的,但大家最终认识到,过于强调灵活性会导致大型项目难以维护:要通过研究代码搞清楚当时解决复杂问题的人是怎么想的,既困难又麻烦,还会耗费大量的时间

经验丰富的程序员倡导尽可能避繁就简。

Python社区的理念都包含在Tim Peters撰写的“Python之禅”中。要获悉这些有关编写优秀Python代码的指导原则,只需在解释器中执行命令import this:

import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

你可以将余生都用来学习Python和编程的纷繁难懂之处,但这样你什么项目都完不成。
不要企图编写完美无缺的代码;先编写行之有效的代码,再决定是对其做进一步改进,还是转而去编写新代码

列表

列表由一系列按特定顺序排列的元素组成。
在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。

访问列表元素

列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。
要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
['trek', 'cannondale', 'redline', 'specialized']
trek
Trek

注意:

  • Python列表索引从0开始,而不是1
  • 从Python列表的最后一个元素开始访问可以一次使用索引-1,-2,-3…

编辑列表

创建的大多数列表都将是动态的,这意味着列表创建后,将随着程序的运行增删元素:创建一个游戏,要求玩家射杀从天而降的外星人;为此,可在开始时将一些外星人存储在列表中,然后每当有外星人被射杀时,都将其从列表中删除,而每次有新的外星人出现在屏幕上时,都将其添加到列表中。在整个游戏运行期间,外星人列表的长度将不断变化。

修改列表元素

要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值:

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles[2] = 'fenghuang'
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'fenghuang', 'specialized']
添加元素

你可能出于众多原因要在列表中添加新元素,例如,你可能希望游戏中出现新的外星人、添加可视化数据或给网站添加新注册的用户。

末尾添加

方法append()动态的将元素添加在列表的尾部:

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
bicycles.append('fenghuang')
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'redline', 'specialized', 'fenghuang']

创建一个空列表,依次字末尾添加元素,这种方式很常见,例如为控制用户,可首先创建一个空列表,用于存储用户将要输入的值,然后将用户提供的每个新值附加到列表中。

列表中插入元素

方法insert()可在列表的任何位置添加新元素:

motorcycles = ['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']

方法insert()在索引0处添加空间,并将值’ducati’存储到这个地方。

删除元素

需要从列表中删除一个或多个元素。
家将空中的一个外星人射杀后,你很可能要将其从存活的外星人列表中删除;当用户在你创建的Web应用中注销其账户时,你需要将该用户从活跃用户列表中删除。

使用del语句删除元素

如果知道要删除的元素在列表中的位置,可使用del语句:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

使用del语句将值从列表中删除后,就无法再访问它了。

使用pop()删除元素

有时候,你要将元素从列表中删除,并接着使用它的值
你可能需要获取刚被射杀的外星人的x和y坐标,以便在相应的位置显示爆炸效果;在Web应用程序中,你可能要将用户从活跃成员列表中删除,并将其加入到非活跃成员列表中。
方法pop()可删除列表末尾的元素,并让你能够接着使用它。
术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycles = motorcycles.pop()
print(motorcycles)
print(popped_motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
弹出列表中任何位置处的元素

pop()是从列表的尾部删除一个元素。
可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
每当你使用pop()时,被弹出的元素就不再在列表中了。
如果你不确定该使用del语句还是pop()方法,下面是一个简单的判断标准:

  • 如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句
  • 如果你要在删除元素后还能继续使用它,就使用方法pop()。
根据值删除元素

如果你只知道要删除的元素的值,可使用方法remove()。
方法remove()只删除第一个指定的值,如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
使用remove()从列表中删除元素时,也可接着使用它的值。

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

列表排序

sort()

Python方法sort()可以对列表进行永久性排序修改。

按字母表顺序排序,直接使用即可:

cars = ['bmw','adui','toyota','subaru']
print(cars)
cars.sort()
print(cars)
['bmw', 'adui', 'toyota', 'subaru']
['adui', 'bmw', 'subaru', 'toyota']

按字母表倒序排序,向sort()方法传递参数reverse=True:

cars = ['bmw','adui','toyota','subaru']
print(cars)
cars.sort(reverse=True)
print(cars)
['bmw', 'adui', 'toyota', 'subaru']
['toyota', 'subaru', 'bmw', 'adui']
sorted()

函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。

cars = ['bmw','adui','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
Here is the original list:
['bmw', 'adui', 'toyota', 'subaru']

Here is the sorted list:
['adui', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'adui', 'toyota', 'subaru']
reverse()

要反转列表元素的排列顺序,可使用方法reverse()。
reverse()不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序。
方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse()即可

cars = ['bmw','adui','toyota','subaru']
print(cars)
cars = cars.reverse()
print(cars)
['bmw', 'adui', 'toyota', 'subaru']
['subaru', 'toyota', 'adui', 'bmw']

列表长度

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

cars = ['bmw','adui','toyota','subaru']
print(len(cars))
4

遍历列表

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

magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician.title()+',that was a great trick!')
    print("I can't wait to see your next trick,"+magician.title()+".\n" )
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.

这行代码让Python从列表magicians中取出一个名字,并将其存储在变量magician中。
你可以这样解读这些代码:对于列表magicians中的每位魔术师,都将其名字打印出来。
刚开始使用循环时请牢记,对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次,且通常速度非常快。

在for循环中,想包含多少行代码都可以。在代码行for magician in magicians后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。

在for循环后面,没有缩进的代码都只执行一次,而不会重复执行:

magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician.title()+',that was a great trick!')
    print("I can't wait to see your next trick,"+magician.title()+".\n" )
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!

注意问题

  • 忘记缩进
  • 忘记缩进额外的代码行:代码不会报错,但是有逻辑错误
  • 不必要的缩进
  • 循环后不必要的缩进
  • 遗漏了冒号

循环函数range()

Python函数range()让你能够轻松地生成一系列的数字。

for value in range(5):
    print(value)
0
1
2
3
4

注意:在这个示例中,range()只是打印数字1~4,这是你在编程语言中经常看到的差一行为的结果。

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

for value in range(1,6):
    print(value)
1
2
3
4
5

使用range()创建数字列表

可使用函数list()将range()的结果直接转换为列表。

numbers = list(range(2,11,2))
print(numbers)
[2, 4, 6, 8, 10]

函数range()从2开始数,然后不断地加2,直到达到或超过终值(11)。

使用函数range()创建一个平方数字的集合:

squares = []
for square in range(1,11):
    square = square**2
    squares.append(square)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表的数字计算

有几个专门用于处理数字列表的Python函数:最大值、最小值、求和

digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45

列表解析

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

squares = [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引:

players = ['charles','martina','michael','florence','eli']
print(players[0:3])
['charles', 'martina', 'michael']

如果你没有指定第一个索引,Python将自动从列表开头开始。
要让切片终止于列表末尾,也可使用类似的语法。

如果要遍历列表的部分元素,可在for循环中使用切片:

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
复制列表

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:]):

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
my_foods.append('KFC')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'KFC']

My friend's favorite are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

不使用复制列表达不到这种效果:

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods
my_foods.append('KFC')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'KFC', 'ice cream']

My friend's favorite are:
['pizza', 'falafel', 'carrot cake', 'KFC', 'ice cream']

元组

列表非常适合用于存储在程序运行期间可能变化的数据集。
列表是可以修改的。
Python将不能修改的值称为不可变的,而不可变的列表被称为元组
元组看起来犹如列表,但使用圆括号而不是方括号来标识。

dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
200
50

代码格式

  • 建议每级缩进都使用四个空格
  • 制表符和空格不要杂合使用
  • 建议每行Python代码不超过80字符
  • 建议注释的行长都不超过72字符
  • 要将程序的不同部分分开,可使用空行(空行不会影响代码的运行,但会影响代码的可读性)

if语句

在Python中,if语句让你能够检查程序的当前状态,并据此采取相应的措施:

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
Audi
BMW
Subaru
Toyota

条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。
如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码:

car = 'audi'
print(car == 'bmw')
False

一个等号是陈述,可解读为“将变量car的值设置为’audi’”;两个等号是发问,可解读为“变量car的值是’bmw’吗?”。

检查特定值包含\不包含

结束用户的注册过程前,可能需要检查他提供的用户名是否已包含在用户名列表中。
要判断特定的值是否已包含在列表中,可使用关键字in/not in

cars = ['audi','bmw','subaru','toyota']
answer = 'dudi' in cars
print(answer)
False

布尔表达式

布尔表达式,是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为True,要么为False。
布尔值通常用于记录条件:

game_actice = True
can_edit = False

最简单的if语句

if conditional_test:
    do something

在第1行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。如果条件测试的结果为True,Python就会执行紧跟在if语句后面的代码;否则Python将忽略这些代码。
在if语句中,缩进的作用与for循环中相同。如果测试通过了,将执行if语句后面所有缩进的代码行,否则将忽略它们:

if-else语句

if-else语句块类似于简单的if语句,但其中的else语句让你能够指定条件测试未通过时要执行的操作。

if conditional_test:
    do something
else:
    do other

if-else结构非常适合用于要让Python执行两种操作之一的情形。在这种简单的if-else结构中,总是会执行两个操作中的一个。

if-elif-else语句

经常需要检查超过两个的情形,为此可使用Python提供的if-elif-else结构。
Python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。
测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。

if condition1:
    do something1
elif condition2:
    do something2
else:
    do somethong3
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $"+str(price)+'.')
Your admission cost is $5.

注意可以是使用多个else代码块,
也可以省略else代码块。

如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。

测试多个条件

if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。
需要测试多个条件时,应使用一系列不包含elif和else代码块的简单if语句,需要在每个条件为True时都采取相应措施时,适合使用这种方法:

requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
print("Finished making your pizza!")
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

如果使用if-elif-else结构,代码将不能正确地运行,因为有一个测试通过后,就会跳过余下的测试:

requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
print("Finished making your pizza!")
Adding mushrooms.
Finished making your pizza!

如果只想执行一个代码块,就使用if-elif-else结构;
如果要运行多个代码块,就使用一系列独立的if语句。

列表结合if语句

通过创建一个列表,在其中包含顾客点的配料,并使用一个循环来指出添加到比萨中的配料,可以以极高的效率编写这样的代码:

requested_toppings = ['mushrooms', 'extra cheese','green peppers']
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding "+requested_topping+".")
print("Finished making your pizza!")
Adding mushrooms.
Adding extra cheese.
Srry, we are out of green peppers right now.
Finished making your pizza!

确定列表是否为空:

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("Finished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza?

在if语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False

使用多个列表
场景:如果顾客要在比萨中添加店里没有的料

available_toppings = ('mushrooms', 'olives', 'green peppers',
                      'pepperoni', 'pineapple', 'extra cheese')
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + ".")
    else:
        print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
dding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

字典

在Python中,字典是一系列花括号{}表示的键—值对
键和值之间用冒号分隔,而键—值对之间用逗号分隔。

使用字典

访问字典中的值
alien_0 = {'color':'green','point':5}
print(alien_0['color'])
green
添加键值对

字典是一种动态结构,可随时在其中添加键—值对。要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值。

alien_0 = {'color':'green','point':5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'point': 5}
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}

通常为了方便和必要,我们可以创建一个空字典,再往里面添加键值对。

修改字典中的值

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

alien_0 = { 'x_position': 0, 'y_position': 25,'speed':''}
print(alien_0)
# 外星人初始位置
print("Original x-positon: "+str(alien_0['x_position']))
# 给外星人一个速度并打印外星人字典
alien_0['speed'] = 'slow'
print(alien_0)
# 向右移动外星人
# 根据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
    x_increament = 1
elif alien_0['speed'] == 'medium':
    x_increament = 2
else:
    # 外星人的速度一定很快了
    x_increament = 3
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increament
print("New x-position: "+str(alien_0['x_position']))
{'x_position': 0, 'y_position': 25, 'speed': ''}
Original x-positon: 0
{'x_position': 0, 'y_position': 25, 'speed': 'slow'}
New x-position: 1
删除键值对

对于字典中不再需要的信息,可使用del语句将相应的键—值对彻底删除:

alien_0 = {'color':'green','point':5,'x_position': 0, 'y_position': 25,'speed':''}
print(alien_0)
del alien_0['point']
print(alien_0)
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25, 'speed': ''}
{'color': 'green', 'x_position': 0, 'y_position': 25, 'speed': ''}

注意 删除的键—值对永远消失了

由类似对象组成的字典

较大的字典可以放在多行中:

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
print("edward's favorite language is "+
      favorite_language['edward'].title()+
      ".")
edward's favorite language is Ruby.

如何将较长的print语句分成多行:
单词print比大多数字典名都短,因此让输出的第一部分紧跟在左括号后面是合理的;请选择在合适的地方拆分要打印的内容,并在第一行末尾加上一个拼接运算符(+),按回车键进入print语句的后续各行,并使用Tab键将它们对齐并缩进一级。指定要打印的所有内容后,在print语句的最后一行末尾加上右括号。

遍历字典

遍历所有的键—值对

要编写用于遍历字典的for循环,可声明两个变量,用于存储键—值对中的键和值:(对于这两个变量,可使用任何名称

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name,language in favorite_language.items():
    print("\n"+name.title()+" 's favorite language is "+language.title()+".")

Jen 's favorite language is Python.

Sarah 's favorite language is C.

Edward 's favorite language is Ruby.

Phil 's favorite language is Python.
遍历字典中所有键

在不需要使用字典中的值时,方法keys()很有用。
遍历字典时,会默认遍历所有的键:

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
friends = ['phil','sarah']
for name in favorite_language.keys():
    print(name.title())
    if name in friends:
        print(" Hi "+name.title()+
              ", I see you favorite language is "+
              favorite_language[name].title()+"!")
Jen
Sarah
 Hi Sarah, I see you favorite language is C!
Edward
Phil
 Hi Phil, I see you favorite language is Python!
按顺序遍历字典中的所有键

但获取字典的元素时,获取顺序是不可预测的。
要以特定的顺序返回元素,一种办法是在for循环中用sorter()方法对返回的键进行排序:

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in sorted(favorite_language.keys()):
    print(name.title())
Edward
Jen
Phil
Sarah
遍历字典中的所有值

使用方法values(),它返回一个值列表,而不包含任何键:

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for language in favorite_language.values():
    print(language.title())
Python
C
Ruby
Python

嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套

# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_num in range(30):
    new_alien = {'color':'green','speed':'slow','point':15,}
    aliens.append(new_alien)
# 修改外星人的属性
for alien in aliens[:8]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'slow'
        alien['point'] = 20
    for alien in aliens[:4]:
        if alien['color'] == 'yellow':
            alien['color'] = 'red'
            alien['speed'] = 'fast'
            alien['point'] = 30
# 显示前5个外星人
for alien in aliens[:10]:
    print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens: "+str(len(aliens)))
{'color': 'red', 'speed': 'fast', 'point': 30}
{'color': 'red', 'speed': 'fast', 'point': 30}
{'color': 'red', 'speed': 'fast', 'point': 30}
{'color': 'red', 'speed': 'fast', 'point': 30}
{'color': 'yellow', 'speed': 'slow', 'point': 20}
{'color': 'yellow', 'speed': 'slow', 'point': 20}
{'color': 'yellow', 'speed': 'slow', 'point': 20}
{'color': 'yellow', 'speed': 'slow', 'point': 20}
{'color': 'green', 'speed': 'slow', 'point': 15}
{'color': 'green', 'speed': 'slow', 'point': 15}
...
Total number of aliens: 30

在字典中存储列表

有时候,需要将列表存储在字典中,而不是将字典存储在列表中。
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

# 存储所点披萨信息
pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese','chicken']
}
# 描述所点的披萨
print("You orderded a "+pizza['crust']+"-crust pizza "+
      "with the following toppings:")
for topping in pizza['toppings']:
    print("\t"+topping)
You orderded a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese
	chicken

输出每个人喜欢的语言示例:

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskelll']
    }
for name,languages in favorite_languages.items():
    if len(languages) == 1:
        print("\n"+name.title()+"'s favorite language is \n\t"+languages[0].title())
    else:
        print("\n"+name.title()+"'s favorite language are")
        for language in languages:
            print("\t"+language.title())
Jen's favorite language are
	Python
	Ruby

Sarah's favorite language is 
	C

Edward's favorite language are
	Ruby
	Go

Phil's favorite language are
	Python
	Haskelll

在字典中存储字典

可在字典中嵌套字典,但这样做时,代码可能很快复杂起来。
例如,如果有多个网站用户,每个都有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值:

user = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princetion'
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris'
    },

}
for username,user_info in user.items():
    print("\nUserame:"+username.title())
    full_name = user_info['first']+" "+user_info['last']
    location = user_info['location']
    print("\tFull name: "+full_name.title())
    print("\tLocation: "+location.title())
Userame:Aeinstein
	Full name: Albert Einstein
	Location: Princetion

Userame:Mcurie
	Full name: Marie Curie
	Location: Paris

集合

获取一个剔除重复项的列表,可使用集合(set)
集合类似于列表,但每个元素都必须是独一无二的:

favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("The following language have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())
The following language have been mentioned:
C
Ruby
Python

通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。

用户输入与while循环

程序接受用户输入,可以自由处理数据。
while循环让程序不断地运行,直到指定的条件不满足为止。

用户输入

函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。

prompt = "If you tell us who you are, we can persionalize the message you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("Hellp")
If you tell us who you are, we can persionalize the message you see.
What is your first name? 

运算符+=在存储在prompt中的字符串末尾附加一个字符串。

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

使用函数input()时,Python将用户输入解读为字符串:

age = input("How old are you?")
print(type(age))
if age >= 18:
    print("You're an adult")
How old are you?21
Traceback (most recent call last):
  File "D:/MINE/python/new201103/Demo.py", line 146, in <module>
    if age >= 18:
TypeError: '>=' not supported between instances of 'str' and 'int'
<class 'str'>

用户输入的是数字21,程序返回的是字符串“21”,试图作比较时会报错,如上。
可以用int()接受用户输入数字:

age = input("How old are you?")
age = int(age)
print(type(age))
if age >= 18:
    print("You're an adult")
How old are you?21
<class 'int'>
You're an adult

求模运算符

处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数,求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少
判断一个数是气数还是偶数的实例:

number = input("Please enter a number,and I'll tell you if it's even or odd:")
number = int(number)
if number % 2 == 0:
    print("\nThe number "+str(number)+" is even.")
else:
    print("\nThe number "+str(number)+" is odd.")
Please enter a number,and I'll tell you if it's even or odd:42

The number 42 is even.

在Python 2.7中获取输入

Python 2.7中应使用函数raw_input()来提示用户输入。这个函数与Python 3中的input()一样,也将输入解读为字符串。
Python 2.7也包含函数input(),但它将用户输入解读为Python代码,并尝试运行它们。

while循环

for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止:

promot = "\nTell me something, and I will repeat it back to you:"
promot += "\nEnter 'quit' to end the program. "
message = ""
while message != "quit":
    message = input(promot)
    if message != 'quit':
        print(message)

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone
Hello everyone

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again
Hello again

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

Process finished with exit code 0

使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。
让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值