25.更多更多的练习——自定义模块
前言
一些关于函数和变量的练习——写程序,逐行研究,弄懂它。
一、Atom文本编辑器
def break_words(stuff):
"""This is 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_words(words):
"""Print the first words after popping if off."""
word = words.pop(0)
print(word)
def print_last_words(words):
"""Print the last words after popping if off."""
word = words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes in a full sentence and return the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Print the first and last of the sentence."""
words = break_words(sentence)
print_first_words(words)
print_last_words(words)
def print_first_and_last_sorted(sentence):
"""Sorts the woeds the print the first and last one."""
words = sort_sentence(sentence)
print_first_words(words)
print_last_words(words)
二、运行Python程序
首先以正常的方式在Window上键入Python运行。
python ex25.py
这个习题将在Python解释器里用交互的方式个ex25.py模块进行交流。在shell里运行Python:
在>>>提示符录入Python代码:
import ex25
sentence = "All good things come to those who wait."
words = ex25.break_words(sentence)
words
sorted_words = ex25.sort_words(words)
sorted_words
ex25.print_first_words(words)
ex25.print_last_words(words)
words
ex25.print_first_words(sorted_words)
ex25.print_last_words(sorted_words)
sorted_words
sorted_words = ex25.sort_sentence(sentence)
sorted_words
ex25.print_first_and_last(sentence)
ex25.print_first_and_last_sorted(sentence)
三、程序模块说明
1、help( )
继续执行help(ex25.py)和help(ex25.break_words),这是得到模块帮助文档的方法。所谓帮助文档就是定义函数时放在“”“之间的字符串,这些特殊的字符串也被称作文档注释(documentation comment)。
2、from * import *
重复键入ex25比较麻烦,有一个捷径就是用from ex25 import * 的方法导入模块,这相当于告诉程序:“要把ex25中的所有东西导入进来”。
3、return和print( )
函数的return会给调用该函数的代码行一个结果:函数通过参数接收输入,通过return返回输出。print()和它毫无关系,只是在终端打印它的内容。
总结
以上内容介绍了Python的自定义模块的使用练习,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。