更多课程 选择中心


Python培训

400-111-8989

Python入门三部曲,教你快速高效入门Python开发

  • 发布:Python进阶大神
  • 来源:逆水寒Say
  • 时间:2017-10-30 16:23

###为什么要学习Python

Python十分强大,学习python理由我就列举如下几条:

1. 可以做服务器后台

2. 可以做自动化工具

3. 可以网络爬取数据

4. 可以做web网站

5. 可以进行数据分析

6. 可以人工智能研究

>个人以前学的东西太杂了:Android(主),java,php,go,ios,前端。现在准备专挑一门语言进行深入。在Android行情没落的时候,在人工智能与大数据到来的时候,学习Python也许是一个不错的选择.从前端到后台,什么都能干。**python在手,天下我有!**

#对于新手来说是快速学习而不是折腾IDE,Pycharm集成了所有python需要用的插件,以及第三方库,一键安装一系列你需要的库像Numpy,Requests,MatplotLib等,让你快速开发不折腾与环境,

###选择Python IDE

一直以来对JetBranis公司开发的一些IDE情有独钟,虽然他们的IDE对电脑要求配置非常高,但不介意,像他们的IDE涵盖大部分主流开发环境并且也是最好的IDE.Android ,java,php,python,go,ios,前端,他们公司都有对应的IDE,而且他们的IDE工具都是一脉相承的,你会使用其中一个,那么其它的IDE基本也是相同的用法。

###Python环境安装

今天开发专注Python学习,所以jetbrains公司的**Pycharm**当然是我开发的首选工具了

1. **Pytharm win版 [下载地址](#/pycharm/download/#section=windows)**

2. 然后需要一个激活码,这里我选择一个server,输入地址`#/` 即可激活.

3. 然后启动IDE这里打开后会提示一个错误,说你没有选择python解释器 `No Python interpreter selected`

4. 打开python官网,下载python解释器**[官网](#/)**,这里我下载的是3.6版本的,虽然大多数成熟的库还是在用2.x版本,但既然是学习,肯定是要面向未来 ,所以我这里选择的是3.6版本

5. 双击安装Python解释器文件。

6. 安装完毕后,在IDE启动界面显示错误的地方,添加add local来选择解释器,然后点击Create

7. 这样python环境搭建完毕

尼玛:太简单了,就忘了截图,其实搭建真的是非常简单,无图就无图吧。

最后上一句经典代码hello world效果图

###1.起步

2.变量和简单数据类型

1.变量

message = "hello world python"

print(message)

2.命名

1.命名与使用

2.使用变量时避免命名错误

3.字符串

1.使用方法修改字符串的大小写

name = 'ada lovelace'

print(name.title())

输出得到:

Ada Lovelace

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

print(name.upper())

print(name.lower())

得到:

ADA LOVELACE

ada lovelace

2.拼接字符串

用“+” 来拼接字符串

“\t,\n”来空格与换行

3.删除空白

rstrip() 删除末尾的空白

lstrip() 删除头部的空白

strip() 删除字符串两端的空白

msg = ' python '

print(msg.rstrip())

print(msg.lstrip())

print(msg.strip())

得到

python

python

python

4.使用字符串避免语法错误

单引号与单引号一对,

双引号与双引号是一对,

一般要成对出现,且。

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

age = 23

msg = "Happy "+str(age)+" rd Birthday" # 必须使用str()否则python识别不了

print(msg)

3.列表简介

1.列表是什么

bicycles = ['trek','cannondale','redline','specialized']

print(bicycles)

1.访问列表元素

print(bicycles[0])

得到

trek

2.索引从0而不是1开始

2.修改,添加和删除元素

1.修改列表元素

names =['zhangsan','lisi','wangwu','zhaoliu']

print(names)

names[0] = 'zhangsanfeng'

print(names)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu']

2.列表中添加元素

在列表末尾添加元素

names.append('qianda')

print(names)

得到:

['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu', 'qianda']

cars = []

cars.append('honda')

cars.append('honda2')

cars.append('honda3')

print(cars)

得到

['honda', 'honda2', 'honda3']

在列表中插入元素

cars.insert(0,'honda0')

print(cars)

得到:

['honda0', 'honda', 'honda2', 'honda3']

3.2.3列表中删除元素

nicks =['zhangsan','lisi','wangwu','zhaoliu']

del nicks[0]

print(nicks)

得到:

['lisi', 'wangwu', 'zhaoliu']

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

poped_nicks = nicks.pop();

print(nicks)

print(poped_nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhangsan', 'lisi', 'wangwu']

zhaoliu

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

使用方法pop()删除元素

有时候要将元素从列表中删除,并接着使用它的值,方法pop()可删除列表末尾的元素,并让你能够接着使用它。

使用del语句删除元素

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

poped_nicks = nicks.pop(0)

print('The first name is '+poped_nicks.title()+'.')

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

The first name is Zhangsan.

如果不确定使用del语句还是pop()方法,有一个简单的标准:如果你要从列表中删除的一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()

根据值删除元素

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

nicks.remove('lisi')

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhangsan', 'wangwu', 'zhaoliu']

3.组织列表

1.使用方法sort()对列表进行永久性排序—按字母排序

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

nicks.sort();

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['lisi', 'wangwu', 'zhangsan', 'zhaoliu']

还可以按字母顺序相反的顺序排列列表元素,只需要向sort()方法传递参数reverse = True

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

nicks.sort(reverse = True);

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhaoliu', 'zhangsan', 'wangwu', 'lisi']

2.使用方法sorted()对列表进行临时排序—按字母排序

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

print(sorted(nicks))

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['lisi', 'wangwu', 'zhangsan', 'zhaoliu']

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

还可以相反顺序临时排序

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

print(sorted(nicks,reverse = True))

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhaoliu', 'zhangsan', 'wangwu', 'lisi']

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

3.倒着打印列表,按元素反转列表排序

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks)

nicks.reverse()

print(nicks)

得到:

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['zhaoliu', 'wangwu', 'lisi', 'zhangsan']

方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复原来的排列顺序,只需要再次调用reverse()

4.确定列表的长度

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(len(nicks))

得到:4

4.使用列表时避免索引错误

注意元素的个数,另外访问最后一个元素时,都可使用索引-1,倒数第2个可以使用索引-2,依次类推

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks[-1])

得到:

zhaoliu

4.操作列表

1.遍历整个列表

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick)

得到:

zhangsan

lisi

wangwu

zhaoliu

for cat in cats:

for dog in dogs

for item in list_of_items

使用单数和复数的式名称可帮助判断代码段处理的是单个列表元素还是整个列表。

1.在for循坏环中执行更多的操作

在每条记录中打印一条消息。

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

得到:

Zhangsan, welcome to china

Lisi, welcome to china

Wangwu, welcome to china

Zhaoliu, welcome to china

执行多行代码,这里需要注意一下,接下来的代码都是需要缩进的

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

print("hello,python")

得到:

Zhangsan, welcome to china

hello,python

Lisi, welcome to china

hello,python

Wangwu, welcome to china

hello,python

Zhaoliu, welcome to china

hello,python

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

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

print("hello,python")

print("print all message and print finish!")

得到:

Zhangsan, welcome to china

hello,python

Lisi, welcome to china

hello,python

Wangwu, welcome to china

hello,python

Zhaoliu, welcome to china

hello,python

print all message and print finish!

可以看到最后一条要打印的消息只打印一次,最后一条没有缩进,因此只打印一次

2.避免缩进错误

忘记缩进

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

得到:

File "/Users/liuking/Documents/python/python_learn/test.py", line 22

print(nick.title()+", welcome to china")

^

IndentationError: expected an indented block

忘记缩进额外的代码行

其实想打印两行的消息,结果只打印了一行,print("hello,python") 忘记缩进了,结果只是最后一条打印了这条消息

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

print("hello,python")

得到:

Zhangsan, welcome to china

Lisi, welcome to china

Wangwu, welcome to china

Zhaoliu, welcome to china

hello,python

不必要的缩进

message = 'hello python world'

print(message)

得到:

File "/Users/liuking/Documents/python/python_learn/test.py", line 20

print(message)

^

IndentationError: unexpected indent

循环后不必要的缩进

第三个打印的消息没有缩进,结果每一行都被打印出来了。

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks:

print(nick.title()+", welcome to china")

print("hello,python")

print("print all message and print finish!")

得到:

Zhangsan, welcome to china

hello,python

print all message and print finish!

Lisi, welcome to china

hello,python

print all message and print finish!

Wangwu, welcome to china

hello,python

print all message and print finish!

Zhaoliu, welcome to china

hello,python

print all message and print finish!

遗漏了冒号

漏掉了冒号,python不知道程序意欲何为。

3.创建数值列表

1.使用函数range()

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

for value in range(1,5):

print(value)

得到:

1

2

3

4

只打印了1〜4 函数range()从指定的第一个值开始数,并在到达你指定的你第二个值后停止。

2.使用range()创建数字列表

要创建数字列表,可使用函数list()将range()的结果直接转换为列表,如果将range()作为list()的参数,输出将为一个数字列表。

numbers = list(range(1,6))

print(numbers)

得到:

[1, 2, 3, 4, 5]

把10个整数的平方加入列表中,并打印出来

squares = []

numbers = range(1,11)

for number in numbers:

squares.append(number**2)

print(squares)

得到:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

最小值,最大值,求和

digits = [1,2,3,4,5,6,7,8,9,0]

print(min(digits))

print(max(digits))

print(sum(digits))

得到:

0

9

45

4.使用列表的一部分

1.切片

nicks =['zhangsan','lisi','wangwu','zhaoliu']

print(nicks[0:3]) 前一个数从0开始,后一个数从1开始数

print(nicks[2:3]) 从2开始,截止到第4个元素

print(nicks[2:]) 从2开始,没有指定截止数据,直接数到末尾

print(nicks[:2]) 没有指定开始,默认从0开始

print(nicks[:]) 没有指定开始,也没有指定结束的,直接复制整个列表

print(nicks[-2:]) 从倒数第2个开始

得到:

['zhangsan', 'lisi', 'wangwu']

['wangwu']

['wangwu', 'zhaoliu']

['zhangsan', 'lisi']

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

['wangwu', 'zhaoliu']

2.遍历切片

nicks =['zhangsan','lisi','wangwu','zhaoliu']

for nick in nicks[0:3]:

print(nick.title())

得到:

Zhangsan

Lisi

Wangwu

3.复制列表—-需要特别注意了

nicks =['zhangsan','lisi','wangwu','zhaoliu']

nicks_copy = nicks[:]

print("original nicks")

print(nicks)

print("copy nicks")

print(nicks_copy)

得到:

original nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

copy nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu']

为了核实我们确实有两个列表,

我们可以再添加一下东西

nicks =['zhangsan','lisi','wangwu','zhaoliu']

nicks_copy = nicks[:]

nicks.append('zhangsanfeng')

nicks_copy.append('zhangwuji')

print("original nicks")

print(nicks)

print("copy nicks")

print(nicks_copy)

得到:

original nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng']

copy nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangwuji']

如果我们只是简单的nicks赋值给nicks_copy就不能得到两个列表

nicks =['zhangsan','lisi','wangwu','zhaoliu']

nicks_copy = nicks;

nicks.append('zhangsanfeng')

nicks_copy.append('zhangwuji')

print("original nicks")

print(nicks)

print("copy nicks")

print(nicks_copy)

得到:

original nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']

copy nicks

['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']

因为nicks和nicks_copy都指向同一个列表,所以都打印出了相同的列表,这里要特别注意

5.元组

python将不能修改的值称为不可变的,而不可变的列表被称为元组。有的时候需要创建一系列不可修改的元素,元组可以满足这种需要。

定义元组

元组看起来像列表,但使用圆括号而不是方括号来标识,定义元组后,就可以使用索引来访问其元素。

point = (200,50,300,90)

print(point[0])

print(point[1])

print(point[2])

print(point[-1])

得到:

200

50

300

90

遍历元组中的所有值

points = (200,50,300,90)

for point in points:

print(point)

得到:

200

50

300

90

修改元组变量

虽然不能修改元组的元素,但可以给存储元组的变量赋值。重新定义整个元组。

print("original data")

points = (200,50,300,90)

for point in points:

print(point)

print("\nmodify data")

points = (1,2,3,4)

for point in points:

print(point)

得到:

original data

200

50

300

90

modify data

1

2

3

4

5.if语句

1.条件测试

检查相等用‘==’

检查不相等用‘!=’

检查多个条件

使用and检查多个条件:要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一;如果每个测试都通过了,整个表达式为就为True,如果至少有一个测试没有通过,则整个表达式为False

使用or检查多个条件:至少有一个条件满足,就能通过整修测试,仅当两个测试都没有通过时,使用or的表达式才为False

检查特定值是否包含在列表中,使用关键字in

request_topping = ['mushrooms','onions','pineapple']

print('mushrooms' in request_topping)

print('mush' in request_topping)

得到:

True

False

检查特定值是否不包含在列表中,使用关键字not in

request_topping = ['mushrooms','onions','pineapple']

print('mushrooms' not in request_topping)

print('mush' not in request_topping)

得到:

False

True

2.if语句 主要注意的是代码缩进,

if

if-else

if-elif-else

多个elif代码块

省略else代码块

6.字典

1.字典的简单使用

在Python中字典是一系列的键值对,每一个键都与一个值相关联,与键相关联的值可以是数字,字符串,列表,乃至字典。

访问字典的值

alien_0 = {'color':'green','point':5}

print(alien_0['color'])

得到:

green

添加键值对

alien_0 = {'color':'green','point':5}

print(alien_0)

alien_0['x_point'] = 250

alien_0['y_point'] = 100

print(alien_0)

得到:

{'color': 'green', 'point': 5}

{'color': 'green', 'y_point': 100, 'x_point': 250, 'point': 5}

先创建一个空字典

alien_0 = {}

alien_0['x_point'] = 250

alien_0['y_point'] = 100

print(alien_0)

得到:

{'y_point': 100, 'x_point': 250}

修改字典中的值

alien_0 = {}

alien_0['y_point'] = 100

print(alien_0)

alien_0['y_point'] = 1000

print(alien_0)

得到:

{'y_point': 100}

{'y_point': 1000}

删除-键值对

alien_0 = {'color':'green','point':5}

print(alien_0)

del alien_0['point']

print(alien_0)

得到:

{'color': 'green', 'point': 5}

{'color': 'green'}

2.遍历字典

遍历所有的键值对

values = {'1':'one','2':'two','3':'three','4':'four'}

for value in values.items():

print(value)

for key,value in values.items():

print("\nkey:"+key)

print("value:"+value)

得到:

('1', 'one')

('3', 'three')

('2', 'two')

('4', 'four')

key:1

value:one

key:3

value:three

key:2

value:two

key:4

value:four

1.遍历字典中所有的键

values = {'1':'one','2':'two','3':'three','4':'four'}

for value in values.keys():

print(value)

得到:

1

3

2

4

2.遍历字典中所有的值

values = {'1':'one','2':'two','3':'three','4':'four'}

for value in values.values():

print(value)

得到:

one

three

two

four

3.按顺序遍历字典中所有键

values = {'first':'one','second':'two','three':'three'}

for value in sorted(values.keys()):

print(value)

得到:

first

second

three

7.用户输入和while循环

1.函数input()工作原理

注意:用户输入只能从终端运行,不能直接通过sublime来运行。

os x系统从终端运行python程序:

1. liukingdeMacBook-Pro:~ liuking$ cd Desktop

2. liukingdeMacBook-Pro:Desktop liuking$ ls

3. input.py

4. python3 input.py

5. 输出得到结果

6.

首先:写一段python 文件

name = input("Please enter your name: ")

print("Hello,"+name)

在终端中运行得到:

liukingdeMacBook-Pro:Desktop liuking$ python3 input.py

Please enter your name: kobe bryant

Hello,kobe bryant

liukingdeMacBook-Pro:Desktop liuking$

多行输入展示:

多行展示可以用+=来追加字符串。

prompt = "If you tell us who you are,we can personalize the message you see."

prompt += "\nWhat is your first name?"

name = input(prompt)

print("\n Hello,"+name)

得到:

liukingdeMacBook-Pro:Desktop liuking$ python3 input.py

If you tell us who you are,we can personalize the message you see.

What is your first name?zhang

Hello,zhang

liukingdeMacBook-Pro:Desktop liuking$

注意以下几点:

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

height = input("How tall are you ,in inches? ")

height = int(height)

if height >= 36:

print("\n you're tall enought to ride")

else:

print("\nyou'll be able to ride when you're a little older.")

得到:

liukingdeMacBook-Pro:Desktop liuking$ python3 input.py

How tall are you ,in inches? 43

you're tall enought to ride

liukingdeMacBook-Pro:Desktop liuking$

注意这里使用了int()把数据类型转换了一下,

求模运算符

求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少

>>> 5%3

2

>>> 6%2

0

>>>

2.Whil循环

1.使用While循环

number = input("遍历你输入的数据:")

number = int(number)

begin = int(0)

while begin <= number:

print(begin)

begin += 1;

得到:

liukingdeMacBook-Pro:Desktop liuking$ python3 input.py

遍历你输入的数据:10

0

1

2

3

4

5

6

7

8

9

10

2.让用户选择何时退出

promt = "\nTell me something and I will repeat it back to you:"

promt += "\n Enter 'quit' to end the program."

message = ""

while message != 'quit':

message = input(promt)

if message != 'quit':

print(message)

终端运行得到:

liukingdeMacBook-Pro:DeskTop liuking$ python3 input.py

Tell me something and I will repeat it back to you:

Enter 'quit' to end the program: NBA

NBA

Tell me something and I will repeat it back to you:

Enter 'quit' to end the program: CBA

CBA

Tell me something and I will repeat it back to you:

Enter 'quit' to end the program: quit

liukingdeMacBook-Pro:DeskTop liuking$

其它使用方式:

使用boolean 标记来判断

使用break退出循环

使用continue

3.使用While循环来处理列表和字典

1.在列表之间移动元素

unconfirmed_users = ['one','two','three']

confirmed_users = []

while unconfirmed_users:

current_user = unconfirmed_users.pop()

print("verifying User:"+current_user)

confirmed_users.append(current_user)

# 显示所有已验证用户

print(“\n The following users have been confirmed: “)

for user in confirmed_users:

print(user.title())

得到:

verifying User:three

verifying User:two

verifying User:one

The following users have been confirmed:

Three

Two

One

#####2.使用用户输入来填充字典

responses = {}

设置一个标志,指出调查是否继续

polling_active = True

while polling_active:

# 提示输入被调查者的名字和回答

name = input("\nWhat is your name?")

response = input("Which mountain would you like to climb someday?")

# 将答案存在字典中

responses[name] = response

# 看看是否还有人要参加调查

repeat = input("would you like to let another person respond?(Y/N)")

if repeat == 'N':

polling_active = False

调查结果,显示结果

print("\n----Poll results-----")

for name,response in responses.items():

print(name+" would like to climb "+ response+".")

在终端运行得到:

liukingdeMacBook-Pro:Desktop liuking$ python3 input.py

What is your name?Kobe

Which mountain would you like to climb someday?武当山

would you like to let another person respond?(Y/N)Y

What is your name?姚明

Which mountain would you like to climb someday?灵山

would you like to let another person respond?(Y/N)N

----Poll results-----

Kobe would like to climb 武当山.

姚明 would like to climb 灵山.

liukingdeMacBook-Pro:Desktop liuking$8.函数1.定义函数:使用关键字def来告诉python你要定义一个函数接着指出函数名:如下面函数名是—greet_user()是必须带上的,这里可以可以传递一些参数,也可以不传以:结尾,且与后面所有的缩进构成了函数体调用函数直接写上函数名,如果有参数记得带上参数1. 无参数的函数:

def greet_user():

"""显示简单的函数体"""

print("Hello Python")

greet_user()

得到:

Hello Python

2. 有参数的函数:

def greet_user(username):

"""显示简单的函数体"""

print("Hello Python: "+username)

greet_user('kobe')

得到:

Hello Python: kobe1.实参与形参在函数greet_user()中,变量username是一个形参—-函数完成其工作所需要的一项信息.在代码greet_user(‘kobe’)中,值’kobe’是一个实参。2.传递实参1.位置实参需要注意参数的位置def describe_pet(animal_type,pet_name):

print("\nI have a " + animal_type + ".")

print("My "+ animal_type + "'s name is "+pet_name.title()+".")

describe_pet('dog','james')

describe_pet('dog','iverson')

得到:

I have a dog.

My dog's name is James.

I have a dog.

My dog's name is Iverson.2.关键字实参关键字实参是传递给函数的名称-值对,直接在实参中将名称和值关联起来,因此向函数传递实参时不会混淆。与参数顺序无关。def describe_pet(animal_type,pet_name):

print("\nI have a " + animal_type + ".")

print("My "+ animal_type + "'s name is "+pet_name.title()+".")

describe_pet(pet_name = 'kkkk',animal_type = 'cat')

得到:

I have a cat.

My cat's name is Kkkk.3.默认值编写函数可以给每个形参指定默认值,# 注意已经设置了默认值的参数要放在后面,

def describe_pet2(pet_name,animal_type = 'dog'):

print("\nI have a " + animal_type + ".")

print("My "+ animal_type + "'s name is "+pet_name.title()+".")

describe_pet2('kobe')

describe_pet2(pet_name = 'james')

得到:

I have a dog.

My dog's name is Kobe.

I have a dog.

My dog's name is James.3.返回值1.返回简单值调用返回值的函数时,需要提供一个变量,用于存储返回的值。def get_formatted_name(first_name,last_name):

"""返回整洁的姓名"""

full_name = first_name + '-' +last_name

return full_name.title()

musician = get_formatted_name('kobe','bryant')

print(musician)

得到:

Kobe-Bryant2. 让实参变成可选的def get_formatted_name(first_name,last_name,middle_name= ''):

"""返回整洁的姓名"""

if middle_name:

full_name = first_name +'-'+middle_name+'-'+last_name

else:

full_name = first_name + '-' +last_name

return full_name.title()

musician = get_formatted_name('kobe','bryant')

print(musician)

musician = get_formatted_name('kobe','bryant','vboy')

print(musician)

得到:

Kobe-Bryant

Kobe-Vboy-Bryant3. 返回字典def build_person(first_name,last_name,age = ''):

"""返回一个字典,其中包含有关一个人的信息"""

person = {'first':first_name,'last':last_name}

if age:

person['age'] = age

pass

return person

musician = build_person('kobe','bryant',23)

print(musician)

得到:

{'age': 23, 'last': 'bryant', 'first': 'kobe'}4.结合使用函数和while循环ef get_formatted_name(first_name,last_name,middle_name= ''):

"""返回整洁的姓名"""

if middle_name:

full_name = first_name +'-'+middle_name+'-'+last_name

else:

full_name = first_name + '-' +last_name

return full_name.title()

while True:

print("\nPlease tell me you name:")

first_name = input("first Name: ")

last_name = input("last Name: ")

formatted_name = get_formatted_name(first_name,last_name)

print(formatted_name)

msg = input("do you want to exit (Y/N)")

if msg.upper() == 'Y':

break

终端运行得到:

liukingdeMacBook-Pro:desktop liuking$ python3 input.py

Please tell me you name:

first Name: kobe

last Name: bryant

Kobe-Bryant

do you want to exit (Y/N)n

Please tell me you name:

first Name: chris

last Name: paul

Chris-Paul

do you want to exit (Y/N)y

liukingdeMacBook-Pro:desktop liuking$4. 传递列表1.在函数中修改列表没有使用函数处理# 没有使用函数是这样的。

"""将未确认的用户,进行认证。"""

unconfirmed_users = ['one','two','three']

confirmed_users = []

while unconfirmed_users:

"""处理用户认证操作"""

current_user = unconfirmed_users.pop()

print("verifying User:"+current_user)

confirmed_users.append(current_user)

"""打印认证用户"""

print("\nThe following users have been confirmed: ")

for user in confirmed_users:

print(user.title())

得到:

verifying User:three

verifying User:two

verifying User:one

The following users have been confirmed:

Three

Two

One使用函数处理unconfirmed_users = ['first','second','third']

confirmed_users = []

"""处理用户认证操作"""

def deal_verify_user(unconfirmed_users,confirmed_users):

while unconfirmed_users:

"""处理用户认证操作"""

current_user = unconfirmed_users.pop()

print("verifying User:"+current_user)

confirmed_users.append(current_user)

def print_verify_user(confirmed_users):

for user in confirmed_users:

print(user.title())

deal_verify_user(unconfirmed_users,confirmed_users)

print("\nThe following users have been confirmed: ")

print_verify_user(confirmed_users)

得到:

verifying User:third

verifying User:second

verifying User:first

The following users have been confirmed:

Third

Second

First上面我们发现得到一样的结果,但使用了函数处理可以做到复用,且逻辑比较清晰,易于扩展。2.禁止函数修改列表。如果我们像备份之前的数据,我们就不能修改未认证的用户,这个时候我们可以用切片来处理我们的操作了。unconfirmed_users = ['first','second','third']

confirmed_users = []

"""处理用户认证操作"""

def deal_verify_user(unconfirmed_users,confirmed_users):

while unconfirmed_users:

"""处理用户认证操作"""

current_user = unconfirmed_users.pop()

print("verifying User:"+current_user)

confirmed_users.append(current_user)

def print_user(confirmed_users):

for user in confirmed_users:

print(user.title())

"""这里我们将列表的副本传给函数,列表的原始数据不会被修改"""

deal_verify_user(unconfirmed_users[:],confirmed_users)

print("\nThe following users have been confirmed: ")

print_user(confirmed_users)

print("\n展示原始数据: ")

print_user(unconfirmed_users)

得到:

verifying User:third

verifying User:second

verifying User:first

The following users have been confirmed:

Third

Second

First

展示原始数据:

First

Second

Third5.传递任意数量的实参。有的时候我们不知道函数需要接受多少个实参,python允许函数从调用语句中收集任意数量的实参。“”“这里*toppons指定了一个空元组,将收到的所有值都封装在这个这元组中。”“”

def make_pizza(*toppons):

"""打印顾客点的所有配料"""

print("\nMaking a pizza with the following toppings")

for top in toppons:

print("- "+top.title())

make_pizza('pepperoni')

make_pizza('pepperoni','green peppers','extra cheese')

得到:

Making a pizza with the following toppings

- Pepperoni

Making a pizza with the following toppings

- Pepperoni

- Green Peppers

- Extra Cheese1.结合使用位置实参和任意数量实参,如果要让函数接受不同类型的实参,必须在函数定义中接纳任意数量实参的形参放在最后。python先匹配位置实参和关键字实参,再匹配任意实参,所以这里我们把make_pizza(size,*toppons),位置实参在前,任意实参在后。def make_pizza(size,*toppons):

"""打印顾客点的所有配料"""

print("\nMaking a " + str(size) +"-inch pizza with the following toppings")

for top in toppons:

print("- "+top.title())

make_pizza(18,'pepperoni')

make_pizza(33,'pepperoni','green peppers','extra cheese')

得到:

Making a 18-inch pizza with the following toppings

- Pepperoni

Making a 33-inch pizza with the following toppings

- Pepperoni

- Green Peppers

- Extra Cheese2.使用任意数量的关键字实参。有时候需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量键值对—-调用语句提供了多少就接爱多少。注意:使用任意数量的关键字实参需要使用**声明def build_profile(first,last,**user_info):

"""创建一个字典"""

profile = {}

profile['first_name'] = first

profile['last_name'] = last

for key,value in user_info.items():

profile[key] = value

return profile

info = build_profile('Kobe','bryant',like = 'ball',age = 35)

print(info)

得到:

{'first_name': 'Kobe', 'last_name': 'bryant', 'age': 35, 'like': 'ball'}6.将函数存储在模块中。函数的优点之一是,使用它们可将代码块与主程序分离,通过给函数指定描述性名称,可让主程序容易得多。还可以更进一步,将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块代码。通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点入在程序的高层逻辑上,还能让你在众多不同的程序中重用函数。将函数存储在独立文件后,可与其它程序员共享这些文件而不是整个程序。知道如何导入函数,还能让你使用其它程序员编写的函数库。1.导入整个模块。使用import语句导入了名为module_name.py的整个模块,就可使用下面的语法来使用其中任何一个函数。module_name.function_name() 下面我们创建一个input.py文件。def make_pizza(size,*toppons):

"""打印顾客点的所有配料"""

print("\nMaking a " + str(size) +"-inch pizza with the following toppings")

for top in toppons:

print("- "+top.title())再创建一个test_input.py文件import input

input.make_pizza(18,'pepperoni')

input.make_pizza(33,'pepperoni','green peppers','extra cheese')

得到:

Making a 18-inch pizza with the following toppings

- Pepperoni

Making a 33-inch pizza with the following toppings

- Pepperoni

- Green Peppers

- Extra Cheese上面我们使用import 导入input文件。然后使用文件名input,再调用函数。2.导入特定的函数。还可以导入模块中特写的函数,这种导入方法的语法如下:from module_name import function_name通过用逗号来分隔函数名,可根据需要从模块中导入任意数量的函数:from module_name import function_0,function_1,function_2对于只想导入要使用的函数,代码将类似于下面这样:使用这种语法,调用函数时就无需使用句点,由于我们在import语句中显示地导入了函数make_pizza,因此调用它时只需要指定其名称。from input import make_pizza

make_pizza(18,'pepperoni')

make_pizza(33,'pepperoni','green peppers','extra cheese')

可以得到同样的效果。3.使用as给函数指定别名。有的时候要导入的函数名称可能与程序中现有的名称冲突,或者函数名称太长,可指定简短而独一无二的别名—-函数的另一个名称,类似于外号。指定别名的通用语法是:from module_name import function_name as fn下面我们可以把上面代码修改一下:from input import make_pizza as mp

mp(18,'pepperoni')

mp(33,'pepperoni','green peppers','extra cheese')4.使用as给模块指定别名还可以给模块指定别名。给模块指定别名通用语法如下:import module_name as mn代码如下:import input as put

put.make_pizza(18,'pepperoni')

put.make_pizza(33,'pepperoni','green peppers','extra cheese')5.导入模块中所有的函数使用星号() 运算符可以让Python导入模块中所有的函数:`from module_name import `首先创建有两个函数的文件:def make_pizza(size,*toppons):

"""打印顾客点的所有配料"""

print("\nMaking a " + str(size) +"-inch pizza with the following toppings")

for top in toppons:

print("- "+top.title())

def make_KFC(size,*toppons):

"""打印顾客点的所有配料"""

print("\nMaking a " + str(size) +"-inch KFC with the following toppings")

for top in toppons:

print("- "+top.title())再调用:from input import *

make_pizza(33,'pepperoni','green peppers','extra cheese')

make_KFC(33,'pepperoni','green peppers','extra cheese')

得到:

Making a 33-inch pizza with the following toppings

- Pepperoni

- Green Peppers

- Extra Cheese

Making a 33-inch KFC with the following toppings

- Pepperoni

- Green Peppers

- Extra Cheese注意:import语句中星号让Python将模块中每个函数都复制到这个程序文件中,由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。但使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你项目的中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。最佳做法:要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。这能让代码更清晰,更容易理解和阅读。7.函数编写指南编写函数时,需要牢记几个细节:应给函数指定描述性名称,且只在其中使用小写字母和下划线,描述性名称可帮助你和别人明白代码想要什么,给模块命名时也应按上述约定。给形参指定默认值时,等号两边不要有空格。def function_name(parameter_0,parameter_1='devault value')对于函数调用中的关键字实参,function_name(value_0,parameter='value')完9.类所有的面向对象编辑思想都是一样的,所以这一篇对于是程序员的你一定是非常简单的.9.1 创建和使用类class Car():

"""一次模拟汽车的简单尝试"""

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

self.odometer_reading = 0

def get_descriptive_name(self):

long_name = str(self.year) + ' ' + self.make + ' ' + self.model

return long_name.title()

def update_odometer(self, mileage):

if mileage >= self.odometer_reading:

self.odometer_reading = mileage

else:

print("you can't roll back an odometer!")这里面我就创建了一个一个Car类,不要问我为什么这么写,这就是约定。代码说明def __init__(self, make, model, year):这是一个特殊的函数,使用两个下划线标记主要是为了跟其它的普通函数区分开来。 在java里这个叫构造函数里面有带了几个参数来填充属性,还可以添加默认参数,里面我添加了一个odometer_reading这个属性这里面我添加了两个方法get_descriptive_name 和 update_odometer 这里面必须传入self,这是对自身的一种引用,另外还可以在后面添加若干参数。使用类:byd = Car('byd','byd tang','2017') #实例化Car类

str1 = byd.get_descriptive_name() # 调用类的方法

print(str1.title())

得到结果

2017 Byd Byd Tang

再调用一个带参数的方法

byd.update_odometer(100);

print('move '+str(byd.odometer_reading)+' miles')

得到结果:

move 100 miles9.2 继承直接在Car这个文件里再写一个子类,电动车类:class ElectriCar(Car): #继承Car类

"""电动汽车独特之处"""

def __init__(self, make, model, year, battery_size=100):

"""初始化父类的属性"""

super().__init__(make, model, year) #这里继承父类的属性 和java里的super方法一样

self.battery_size = battery_size # 子类有自己的属性

def descript_batter(self):

print("This car has a " + str(self.battery_size) + " kwh battery.")

def fill_gas_tank(self):

print("i hava a battery")

my_tesla = ElectriCar('tesla', 'model s', '2016')

print(my_tesla.get_descriptive_name()) #引用父类的描述方法

print(my_tesla.fill_gas_tank()) #重写子类的电池方法

得到结果:

2016 Tesla Model S

i hava a battery代码说明在类名称后的括号中写上父类在init方法中使用super方法来继承父类的属性子类自动拥有父类全部的方法子类可以重写父类方法,但方法名一定要写父类一样.9.3 导入类9.4 Python标准库10.文件和异常3.异常异常是使用try-except代码块处理的。try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。使用了try-except代码块时,即便出现异常,程序也将继续运行:显示你编写的友好的错误信息,而不是令用户迷惑的traceback.1.处理ZeroDivisionError异常。print(5/0)2.使用try-except代码块当你认为可能发生了错误时,可编写一个try-except代码块来处理可能引发的异常。处理ZeroDivisionError异常的try-except代码块类似于下面这样:try:

print(5/0)

except Exception, e:

print("You can't divide by zero!")如果程序出现异常,就执行print(“You can’t divide by zero!”),不再是traceback:3.使用异常避免崩溃发生错误时,如果程序还有工作没有完成,妥善处理错误就尤其重要。这种情况经常会现出现在要求用户提供输入的程序中;如果程序能够妥善地处理无效输入,就能再提示用户提供有效输入,而不至于崩溃。下面来一个只执行除法的简单计算器:print("Give me two numbers, and I'll divide them.")

print("Enter 'q' to quit. ")

while True:

first_number = input("\nFirst number: ")

if first_number == 'q':

break;

second_number = input("\nSecond number: ")

if second_number == 'q':

break;

answer = int(first_number)/int(second_number)

print(answer)

得到:

liukingdeMacBook-Pro:desktop liuking$ python3 input.py

Give me two numbers, and I'll divide them.

Enter 'q' to quit.

First number: 4

Second number: 2

2.0

First number: 4

Second number: g

Traceback (most recent call last):

File "input.py", line 244, in <module>

answer = int(first_number)/int(second_number)

ValueError: invalid literal for int() with base 10: 'g'

liukingdeMacBook-Pro:desktop liuking$4. else代码块。通过将可能引发错误的代码放在try-except代码块中,可提高这个程序抵御错误的能力,错误是是执行除法运算的代码行导致的,因此我们需要将它放到try-except代码块中。依赖于try代码块成功执行的代码都放到else代码块中:print("Give me two numbers, and I'll divide them.")

print("Enter 'q' to quit. ")

while True:

first_number = input("\nFirst number: ")

if first_number == 'q':

break;

second_number = input("\nSecond number: ")

if second_number == 'q':

break;

try:

answer = int(first_number)/int(second_number)

except Exception:

print("you can't divide by 0!")

else:

print(answer)

得到:

liukingdeMacBook-Pro:desktop liuking$ python3 input.py

Give me two numbers, and I'll divide them.

Enter 'q' to quit.

First number: 5

Second number: 3

1.6666666666666667

First number: 5

Second number: 0

you can't divide by 0!

First umber:发现异常也能友好的提示给用户。try-except-else代码块的工作原理大致如下:python尝试执行try代码块中的代码;只有可能引发异常的代码才需要放在try语句中。有时候,有一些仅在try代码块成功执行时才需要运行的代码,这些代码应该放在else代码块中。except代码块告诉python,如果它尝试运行try代码块中的代码时引发了指定的异常,该怎么办。通过预测可能发生错误的代码,可编写健壮的程序,它们即便面临无效数据或者缺少资源,也能继续运行,从而能够抵御无意的用户错误和恶意的攻击。5. 处理FileNotFoundError异常。4.存储数据一般都是使用模块json来存储数据。1.使用json.dump()写入数据和json.load()加载数据。使用json.dump()来存储(写入)数据import json

numbers = [2,3,5,7,9,22,44]

file_name = 'numbers.json'

with open(file_name,'w') as f_obj:

json.dump(numbers,f_obj)我们先要导入模块json,再执行,最后可以打开numbers.json文件,看到其内容与python中一样。再使用json.load()读取numbers.json文件:import json

file_name = 'numbers.json'

with open(file_name) as f_obj:

numbers = json.load(f_obj)

print(numbers)

得到:

[2, 3, 5, 7, 9, 22, 44]与我们期望的一致。11.测试代码1.测试1.单元测试和测试用例Python标准库中的模块unitest提供了代码测试工具。单元测试用于测试函数的某个方面是否有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。2.可通过的测试要为函数编写测试用例,可先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。首先我们来写一个方法:def get_formatted_name(first,last):

"""Generate a neatly formatted full name."""

full_name = first + ' ' + last

return full_name.title()再写一个测试用例import unittest

from name_function import get_formatted_name

class NameTestCase(unittest.TestCase):

"""测试name_function.py"""

def test_first_last_name(self):

"""能够正确地处理Janis Joplin这样的姓名吗?"""

formatted_name = get_formatted_name('janis','joplin')

self.assertEqual(formatted_name,'Janis Joplin')

unittest.main()

得到:

.

----------------------------------------------------------------------

Ran 1 test in 0.000s

OK首先我们导入了模块unittest和要测试的函数get_formatted_name()我们创建了一个NameTestCase的类用于包含一系列针对get_formatted_name()的单元测试。可以随便给这个类命名,但最好让它看起来要与测试的函数相关,并包含字样Test。这个类必须继承unittest.TestCase类我们使用了unittest类最有用的功能之一:一个断言方法。断言方法用来核实得到的结果是否与期望的结果一致。第1行的句点表明有一个测试通过了,接下来的一行指出Python运行了一个测试,消耗的时候不到0.01s,最后的OK表明该测试用例中的所有单元测试都通过了。测试方法名为test-first-last-name(),方法名必须以test_开头,这样它才会在我们测试的时候自动运行。这个方法名清楚地指出了它测试的是get_formatted_name()的那个行为,这样如果该测试未通过,我们就会马上知道受影响的是那种类型的姓名。在TestCase类中使用很长的方法名是可以的,这些方法的名称必须是描述性的这才能让你明白测试未通过的时的输出,这些方法由python自动调用,你根本不用编写调用它们的代码。3.不能通过的测试这里我们给出一个不能通过测试的案例def get_formatted_name(first,middle,last):

"""Generate a neatly formatted full name."""

full_name = first + ' ' + middle + ' ' + last

return full_name.title()

再运行一下:

E

======================================================================

ERROR: test_first_last_name (__main__.NameTestCase)

能够正确地处理Janis Joplin这样的姓名吗?

----------------------------------------------------------------------

Traceback (most recent call last):

File "/Users/liuking/Desktop/test_name_function.py", line 11, in test_first_last_name

formatted_name = get_formatted_name('janis','joplin')

TypeError: get_formatted_name() takes exactly 3 arguments (2 given)

----------------------------------------------------------------------

Ran 1 test in 0.000s

FAILED (errors=1)

[Finished in 0.1s with exit code 1]首先指出测试用例中有一个单元测试导致了错误NameTestCase中的test_first_last_name()导致了错误,知道那个测试没有通过至关重要。我们看到了Traceback4. 测试未通过时怎么办测试未通过时怎么办?如果检查的条件没错,测试通过了意味着函数的行为是对的,而测试未通过意味着你编写的新代码有错,因此测试未通过时,不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找到导致函数行为不符合预期的修改。把刚才的函数代码稍作修改:def get_formatted_name(first,last,middle = ''):

"""Generate a neatly formatted full name."""

if middle:

full_name = first + ' ' + middle + ' ' + last

else:

full_name = first + ' ' + last

return full_name.title()

得到:

.

----------------------------------------------------------------------

Ran 1 test in 0.000s

OK

[Finished in 0.1s]又能正确通过测试。5.添加新测试我们为NamesTestCase再添加一个方法:# -*- coding: utf8 -*-

import unittest

from name_function import get_formatted_name

class NameTestCase(unittest.TestCase):

"""测试name_function.py"""

def test_first_last_name(self):

"""能够正确地处理Janis Joplin这样的姓名吗?"""

formatted_name = get_formatted_name('janis','joplin')

self.assertEqual(formatted_name,'Janis Joplin')

def test_first_last_middle_name(self):

"""能够正确地处理Janis Joplin Kobe这样的姓名吗?"""

formatted_name = get_formatted_name('janis','Kobe','joplin')

self.assertEqual(formatted_name,'Janis Joplin Kobe')

unittest.main()

得到:

..

----------------------------------------------------------------------

Ran 2 tests in 0.000s

OK

[Finished in 0.1s]2.测试类1.各种断言方法常用的断言方法,使用这些方法可核实返回的值等于或不等于预期的值,返回的值为True或False,返回的值在列表中或者不在列表中。只能在继承unittest.TestCase的类中使用这些方法unittest Module中的断言方法方法用途assertEqual(a,b)核实 a ==bassertNotEqual(a,b)核实 a !=bassertTrue(x)核实x为TrueassertFalse(x)核实x为FalseassertIn(item,list)核实item在list中assertNotIn(item,list)核实item不在list中2.一个要测试的类类的测试与函数的测试相似—你所做的大部分工作都是测试类中方法的行为,但存在一些不同之处,# -*- coding: utf8 -*-

class AnonymousSurvey():

"""收集匿名调查问卷的答案"""

def __init__(self, question):

self.question = question

self.responses = []

def show_question(self):

"""显示调查问卷"""

print(self.question)

def store_response(self,new_response):

"""存储单份调查问卷"""

self.responses.append(new_response);

def show_results(self):

"""显示收集到的所有答案"""

print("Survey Results:")

for response in self.responses:

print('- '+response)

------------------------------------------------------------------------------------------

from survey import AnonymousSurvey

#定义一人问题,并创建一个表示调查的AnonymousSurvey对象

question = "What language did you first learn to speak?"

my_survey = AnonymousSurvey(question)

my_survey.show_question()

print("Enter 'q' at any time to quit.\n")

while True:

response = input("language: ")

if response == 'q':

break

my_#_response(response)

#显示调查结果:

print("\nThank you to everyone who participated in the survey?")

my_survey.show_results()

运行得到:

在终端运行得到:

What language did you first learn to speak?

Enter 'q' at any time to quit.

language: english

language: chinese

language: japanese

language: q

Thank you to everyone who participated in the survey?

Survey Results:

- english

- chinese

- japanese3.测试AnonymousSurvey类下面来编写一个测试,对AnonymousSurvey类的行为的一个方面进行验证:如果用户面对调查问题时只提供一个答案,这个答案也能被妥善保存,为此我们将在这个答案被保存后,用方法assertIn()来核实包含在答案列表中:import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

"""docstring for ClassName"""

def test_store_single_response(self):

question = "what language did you first learn to speak?"

my_survey = AnonymousSurvey(question)

my_#_response('english')

self.assertIn('english',my_survey.responses)

unittest.main()

运行得到:

.

----------------------------------------------------------------------

Ran 1 test in 0.000s

OK

[Finished in 0.1s]这里我们首先导入了模块unittest以及要测试的类AnonymousSurvey,它也继承于unittest.TestCase第一个测试方法验证调查问题的单个答案被存储后,会包含在调查结果列表中。只能收集一个答案的调查用途不大,我们来核实用户提供的三个答案,也将它们存储。import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

"""docstring for ClassName"""

def test_store_single_response(self):

question = "what language did you first learn to speak?"

my_survey = AnonymousSurvey(question)

my_#_response('english')

self.assertIn('english',my_survey.responses)

def test_store_three_responses(self):

question = "what language did you first learn to speak?"

my_survey = AnonymousSurvey(question)

responses = ['english','chinese','japanese']

for response in responses:

my_#_response(response)

for response in responses:

self.assertIn(response,my_survey.responses)

unittest.main()

运行得到:

..

----------------------------------------------------------------------

Ran 2 tests in 0.000s

OK

[Finished in 0.1s]4. 方法setUp()在unittest.TestCase类包含方法setUp(),让我们只需要创建这些对象一次,并在每个测试方法中使用他们,如果你在TestCase类中包含了方法setUp(),Python将先运行它,再运行各个以test_打头的方法,这样在我们编写的每个测试方法中都可使用方法setUp()中创建的对象。# -*- coding:utf8 -*-

import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

def setUp(self):

"""创建一个调查对象和一组答案,供使用的测试方法使用。"""

question = "What language did you first learn to speak?"

self.my_survey = AnonymousSurvey(question)

self.responses = ['chinese','english','japanese']

"""docstring for ClassName"""

def test_store_single_response(self):

self.my_#_response(self.responses[0])

self.assertIn(self.responses[0],self.my_survey.responses)

def test_store_three_responses(self):

for response in self.responses:

self.my_#_response(response)

for response in self.responses:

self.assertIn(response,self.my_survey.responses)

unittest.main()

运行得到:

..

----------------------------------------------------------------------

Ran 2 tests in 0.000s

OK

[Finished in 0.1s]方法setUp()让测试方法编写起来更容易,可在setUp()方法中创建一系列并设置他们的属性,再在测试方法中直接使用这些实例,相比于在每个测试方法中都都创建并设置其属性,这要容易得多。

本文内容转载自网络,本着分享与传播的原则,版权归原作者所有,如有侵权请联系我们进行删除!

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:准记者、编程小白的python学习计划
下一篇:Python函数基础知多少 ,Python函数基础知识详解

Python IDE推荐7个你可能会错过的Python IDE

Python面试题之Python中爬虫框架或模块的区别

2021年Python面试题及答案汇总详解

python数据分析,你需要这些工具

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省