Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著

的学习思路和理解,如有不如之处,望指出!!!

本节我们利用前面学习的Python函数(def)知识,做一个简单的模块(module),然后我们从外部调用这个模块的函数。

[TOC]

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# ex25.py
def
"""
This function will break up words for us.
"""
words=stuff.split(' '
return

def
"""
sorts the words.
"""
return

def
"""
prints the first word after popping it off.
"""
word=words.pop(0
print

def
"""
prints the last word after popping it off.
"""
word=words.pop(-1
print

def
"""
takes in a full sentence and returns the sorted words.
"""
words=break_words(sentence)
return

def
"""
prints the first and last words of the sentence.
"""
words=break_words(sentence)
print_first_word(words)
print_last_word(words)

def
"""
sorts the words then prints the first and last one.
"""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words)

我们来分析下以上代码中,每一个函数的作用

  1. 把句子中的字母分离,然后返回到words

  2. words中的字母重新排序,然后返回到sorted_words

  3. 输出words中存储的第一个字母

  4. 输出words中存储的最后一个字母

  5. 把重新的排序的字母组成一个句子,然后返回到sorted_words

  6. 输出words的第一个和最后一个字母

  7. 输出sorted_words的第一个和最后一个字母

你应该看到的结果

注意:我对上面这个代码文件的命名是test13.py

我们来分析下编译时每一句的作用是什么?

  • 在第5行,将test13.py执行了import,和我们前面介绍的import作用是一样的。在import的时候是不需要加.py后缀的。把test13.py当成一个模块module来使用,在这个模块里定义的函数是可以直接调用的。

  • 第6行创建了一个语句

  • 第7行使用test13调用第一个函数test13.break_words。其中的.符号可以告诉Python:“我要运行test13模块里那个叫break_words的函数。”

  • 第8行只是输入words,而Python会在第9行打印出words这个变量里的内容,输出的结果是一个列表,后面小节会讲到的

  • 第10~11行使用test13.sort_words来得到一个排序过的句子

  • 第13~16行使用test13.print_first_wordtest13.print_last_word将第一个词和最后一个词打印出来

  • 第17行和第8行的作用是一样的,输出words这个变量里的内容

  • 第19行和第21行的作用同上,是打印出第一个词和最后一个词

  • 第23行和第8行的作用类似

  • 第25行调用函数test13.sort_sentence

  • 剩下几行的作用都和前面的作用都类似了

本节要掌握的知识

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

标准写法:

1
list.pop(obj=list[-1

参数:

1
2
3
obj -- 可选参数,要移除列表元素的对象。
默认参数为-1
参数0

示例:

1
2
3
4
5
6
7
8
9
aList = [123
print
# 参数 -1 指向的是 abc
print
# 参数 0 指向的是 123
print
# 参数 1 指向的是 xyz
print
# 参数 2 指向的是 zara

这是**《笨方法学Python》**的第十三篇文章

希望自己可以坚持下去

希望你也可以坚持下去