笨方法学python笔记(3)

来源:互联网 发布:python应用领域 编辑:程序博客网 时间:2024/05/29 15:40

习题25之前几个习题主要是阅读别人写的代码,做好记录,然后记下来,虽然现在可能不太能理解一些语句,但是先过眼有个印象总归没有错。

习题25:老规矩,贴上自己敲出来的代码。敲代码的时候想练练打字,试试不看键盘盲打敲,给无聊枯燥的码代码带来一点乐趣。


def break_words(stuff):"""This function will break up words for us."""words = stuff.split(' ')return wordsdef sort_words(words):"""Sorts the words."""return sorted(words)def print_first_word(words):"""Print thr first word after popping it off."""word = words.pop(0)print worddef print_last_word(words):"""Prints the last word after popping it off."""word = words.pop(-1)print worddef 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(words)print_first_word(words)print_last_word(words)def print_first_and_last_sorted(sentence):"""Sorts the words then print the first and last one."""words = sort_sentence(sentence)print_first_word(words)print_last_word(words)

这是一个由众多函数组成的脚本,根据教程,要求我们用交互式窗口调用这些函数。首先是import模组(module),这里有两个方法,一个是import 脚本名,一个是from 脚本名 import *。用前一种方法导入时,调用函数需要用脚本名.函数名;后一种方法是导入模组中的所有东西,因此在调用函数的时候可以直接用函数名,省去了多次使用脚本名的麻烦。


在做练习的时候,我加入了一个新函数,等到调用时却提示我“name 函数名 is not defined”,令人奇怪。后来查阅了一下资料,是因为import会生成一个.pyc的编译文件,当调用函数时,系统直接从.pyc的文件中调用函数,因此,尽管脚本改动了,但是.pyc文件并没有改动,仍是用的修改前的脚本内容,所以,需要重新加载脚本内容,用reload函数。


于是,试了一下reload函数。

在这里有一点要注意一下。如果先import 脚本名然后reload(脚本名),那么在调用函数的时候仍是用脚本名.函数名;如果先from 脚本名 import *,然后reload(脚本名),系统就会报错,提示“脚本名 is not defined”。如果觉得每次输入脚本名.函数名太麻烦了,那可以先用import 脚本名,然后reload (脚本名),最后再输入from 脚本名 import *。这个顺序不能颠倒,不然就会报错。如下是运行的结果,从图中可以得到印证。



原创粉丝点击