习题23:更多更多的练习

发布时间:2017-11-15 11:12:26编辑:Run阅读(4740)

    代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    def break_words(stuff):
       '''This function will break up words for us.'''
       words = stuff.split(' ')
       return words

    def sort_words(words):
       '''Sorts the words.'''
       return sorted(words)

    def print_first_word(words):
       '''Prints the first word after popping it off.'''
       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)

    这次调用函数,换一种交互式的方法

    进入到py文件的存放目录,我的在E盘下面的test目录

    图片.png

    然后输入python回车进入交互式

    图片.png

    怎么调用,结果如下

    图片.png

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

    1 在第一行执行了import lianxi_23 ,和你之前做过的一样,import导入一个模块,而我们写的lianxi_23.py就是一个模块,注意导入模块的时候不需要加.py,直接写文件名即可

    2 第二行创建了一个sentence字符串

    3 第三行是调用了lianxi_23里面的break_words函数,去处理sentence字符串

    后面的都是一些调用函数方法,这里就不啰嗦了,认真看每一行的代码,仔细体会具体的意思


    常见问题

    有的结果打印出来的结果是None ?

    也许你的函数漏写了最后的return语句,仔细检测代码

    运行时提示 SyntaxError: invalid syntax ?

    这说明你在提示的那行有一个语法错误,可能是漏了半个括号或者引号,也可能是调用的方法写错

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

    这个问题有点复杂,不过在这里words是一个列表,你可以对它进行操作,操作结果也可以被保存下来,所以导致内容改变

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

    print只是屏幕输出而已,一般用来试调结果正不正确,你可以让一个函数既print又return,当你明白这点后,你就明白这个问题其实没什么意义,如果你需要打印到屏幕,那就用print,如果想要返回值,那就使用return

关键字