这个单元不仅仅是编写这样的python程序然后运行这么简单了,这次我们要首先在编译器里面编写一段python代码,然后到shell中去运行。
下面是python程序:
#coding: utf-8
# 首先我们看到这个程序和其他的程序有所不同在于它并不能运行什么,他只是申明了很多函数,我们要做的仅仅是先把它打出来
# 去shell中看看他有没有错,同时在shell中调用它包含的函数。
# 第一个函数:将句子分离,用到split函数,用法为<sentence>.split(<'symbol'>),以空格为标志切割句子。
# 更多用法不妨参见:http://www.runoob.com/python/att-string-split.html
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)
# 第三个函数,打印第一个单词,用到pop函数,pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
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)
下面是在终端里运行的样子,>>>代表我的输入,后面就是我的输出。
jerry:mystuff mazeyu$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
应该思考一下每一行为什么会出现这样的结果了。