笨方法学Python 习题 25: 更多更多的练习

来源:互联网 发布:java质数判断算法 编辑:程序博客网 时间:2024/05/16 07:17
#!usr/bin/python# -*-coding:utf-8-*-def break_words(stuff):"""This function will break up words for us.""""""split()函数语法:str.split(str="",num=string.count(str))[n]参数说明:str:表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量[n]:表示选取第n个分片注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略"""words = stuff.split(" ")return wordsdef sort_words(words):"""Sorts the words.""""""对List进行排序,sort是在原位重新排列列表,而sorted()是产生一个新的列表."""return sorted(words)def print_first_word(words):"""Prints the first word after popping it off.""""""pop()指定删除对象的索引位置"""word = words.pop(0)print (word)def print_last_word(words):"""Prints the last word after popping it off."""word = words.pop(-1)print (word)def sort_sentence(sentence):"""Takes in a full sentence and returns the sorted words."""words = break_words(sentence)return sort_words(words)def print_first_and_last(sentence):"""Prints the first and last words of the sentence."""words = break_words(sentence)print_first_word(words)print_last_word(words)def print_first_and_last_sorted(sentence):"""Sorts the words then prints the first and last one."""words = sort_sentence(sentence)print_first_word(words)print_last_word(words)

运行结果如下:

$ pythonPython 2.5.1 (r251:54863, Feb  6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import ex25>>> sentence = "All good things come to those who wait.">>> words = ex25.break_words(sentence)>>> words['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']>>> sorted_words = ex25.sort_words(words)>>> sorted_words['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']>>> ex25.print_first_word(words)All>>> ex25.print_last_word(words)wait.>>> wrodsTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'wrods' is not defined>>> words['good', 'things', 'come', 'to', 'those', 'who']>>> ex25.print_first_word(sorted_words)All>>> ex25.print_last_word(sorted_words)who>>> sorted_words['come', 'good', 'things', 'those', 'to', 'wait.']>>> sorted_words = ex25.sort_sentence(sentence)>>> sorted_words['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']>>> ex25.print_first_and_last(sentence)Allwait.>>> ex25.print_first_and_last_sorted(sentence)Allwho>>> ^D$

我们来逐行分析一下每一步实现的是什么:

在第 5 行你将自己的 ex25.py 执行了 import,和你做过的其它 import 一样。在 import 的时候你不需要加 .py 后缀。这个过程里,你把 ex25.py 当做了一个“模组(module)”来使用,你在这个模组里定义的函数也可以直接调用出来。

第 6 行你创建了一个用来处理的“句子(sentence)”。

第 7 行你使用 ex25 调用你的第一个函数 ex25.break_words。其中的 . (dot, period)符号可以告诉 Python:“嗨,我要运行 ex25 里的哪个个叫 break_words的函数!”

第 8 行我们只是输入 words,而 python 将在第 9 行打印出这个变量里边有什么。看上去可能会觉得奇怪,不过这其实是一个“列表(list)”,你会在后面的章节中学到它。

10-11 行我们使用 ex25.sort_words 来得到一个排序过的句子。

13-16 行我们使用 ex25.print_first_word 和 ex25.print_last_word 将第一个和最后一个词打印出来。

第 17 行比较有趣。我把 words 变量写错成了 wrods,所以 python 在 18-20 行给了一个错误信息。

21-22 行我们打印出了修改过的词汇列表。第一个和最后一个单词我们已经打印过了,所以在这里没有再次打印出来。

剩下的行你需要自己分析一下,就留作你的加分习题了。


加分习题

①研究答案中没有分析过的行,找出它们的来龙去脉。确认自己明白了自己使用的是模组 ex25 中定义的函数。

在运行时,遇上两个小问题,特此备注:

1)脚本运行好好的,也都确保每行都对齐了,但是运行的时候,却出现语法错误:

IndentationError: unindent does not match any outer indentation level

其实这里就是,空格和TAB对齐冲突的问题,保证代码内全部使用空格或者全部使用TAB键缩进。

2)AttributeError: module ‘*****' has no attribute '*****'

在Python Shell中运行语法时,代码出现错误,修改后重新运行发现依旧出现类似的报错,而且这时候已经确认代码无误的情况下依旧会报错。百度后有建议清楚pyc,但发现没有效果,最终关闭窗口重新执行代码即可。

②试着执行 help(ex25) 和 help(ex25.break_words) 。这是你得到模组帮助文档的方式。 所谓帮助文档就是你定义函数时放在 """ 之间的东西,它们也被称作 documentation comments (文档注解),后面你还会看到更多类似的东西。

Help on module ex25:NAME    ex25 - # -*-coding:utf-8-*-FUNCTIONS    break_words(stuff)        This function will break up words for us.        print_first_and_last(sentence)        Prints the first and last words of the sentence.        print_first_and_last_sorted(sentence)        Sorts the words then prints the first and last one.        print_first_word(words)        Prints the first word after popping it off.        print_last_word(words)        Prints the last word after popping it off.        sort_sentence(sentence)        Takes in a full sentence and returns the sorted words.        sort_words(words)        Sorts the words.FILE    c:\python36\ex25.py

这里打印出第一对“”“ ”“”的内容。

③重复键入 ex25. 是很烦的一件事情。有一个捷径就是用 from ex25 import * 的方式导入模组。这相当于说:“我要把 ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,开一个新的会话,看看你所有的函数是不是已经在那里了。

把你脚本里的内容逐行通过 python 编译器执行,看看会是什么样子。你可以执行CTRL-D (Windows 下是 CTRL-Z)来关闭编译器。


常见问题回答

有的函数打印出来的结果是 None 。

也许你的函数漏写了最后的 return 语句。回到代码中检查一下是不是每一行都写对了。

输入 import ex15 时显示 -bash: import: command not found 。

注意看《你应该看到的结果》部分。我是在 Python 中写的这句,不是在命令行终端直接写的。你要先运行 python 再输入代码。

输入 import ex25.py 时显示 ImportError: No module named ex25.py 。

.py 是不需要的。Python z知道文件是 .py 结尾,所以只要输入 import ex25 即可。

运行时提示 SyntaxError: invalid syntax 。

这说明你在提示的那行有一个语法错误,可能是漏了半个括号或者引号,也可能识别的。一旦看到这种错误,你应该去对应的行检查你的代码,如果这行没问题,就倒着继续往上检查每一行,直到发现问题为止。

函数里的代码不是只在函数里有效吗?为什么 words.pop(0) 这个函数会改变 words 的内容?

这个问题有点复杂,不过在这里 words 是一个列表,你可以对它进行操作,操作结果也可以被保存下来。这和你操作文件时文件的 f.readline() 工作原理差不多。

函数里什么时候该用 print ,什么时候该用 return ?

print 只是屏幕输出而已,你可以让一个函数既 print 又返回值。当你明白这一点后,你就知道这个问题其实没什么意义。如果你想要打印到屏幕,那就使用 print ,如果是想返回值,那就是用 return 。.