前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >习题23:更多更多的练习

习题23:更多更多的练习

作者头像
py3study
发布2018-08-02 14:32:00
5490
发布2018-08-02 14:32:00
举报
文章被收录于专栏:python3python3python3

代码如下

# 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
图片.png

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

图片.png
图片.png

怎么调用,结果如下

图片.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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档