广告
返回顶部
首页 > 资讯 > 后端开发 > Python >习题23:更多更多的练习
  • 226
分享到

习题23:更多更多的练习

更多习题 2023-01-30 21:01:36 226人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

代码如下# coding: utf-8__author__ = 'www.py3study.com'def break_Words(stuff):    '''This funct

代码如下

# 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

--结束END--

本文标题: 习题23:更多更多的练习

本文链接: https://www.lsjlt.com/news/178902.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作