习题 25: 更多更多的练习

阅读原文
我们将做一些关于函数和变量的练习,以确认你真正掌握了这些知识。这节练习对你来说\ 可以说是一本道:写程序,逐行研究,弄懂它。

不过这节练习还是有些不同,你不需要运行它,取而代之,你需要将它导入到 python 里\ 通过自己执行函数的方式运行。

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)

首先以正常的方式 python ex25.py 运行,找出里边的错误,并把它们都改正过来。 然后你需要接着下面的答案章节完成这节练习。

What You Should See

在这次练习中,我们将在你之前用来做算术的 python 编译器里,与你的ex25.py文件交互。你可以这样从终端运行Python:

$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

您的输出应该看起来像我酱婶儿的,>字符(称为提示)后,您可以输入Python代码,它会立即运行。 用这些我要你键入到 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_word(words)
ex25.print_last_word(words)
words
ex25.print_first_word(sorted_words)
ex25.print_last_word(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 行你将自己的 ex25.py 执行了 import,和你做过的其它 import 一样。在 import 的时候 你不需要加 .py 后缀。这个过程里,你把 ex25.py 当做了一个“模组(module)”来使 用,你在这个模组里定义的函数也可以直接调用出来。
  • 第 2 行你创建了一个用来处理的“句子(sentence)”。
  • 第 3 行你使用 ex25 调用你的第一个函数 ex25.break_words\。其中的 . (dot,
    period)符号可以告诉 Python:“嗨,我要运行 ex25 里的哪个个叫 break_words 的函数!”
  • 第 4 行我们只是输入 words,而 python 将在第 13 行打印出这个变量里边有什么。看上去可能 会觉得奇怪,不过这其实是一个“列表(list)”,你会在后面的章节中学到它。
  • 13 行我们使用 ex25.sort_words 来得到一个排序过的句子。
  • 7-8 行我们使用 ex25.print_first_wordex25.print_last_word 将第一个和最后一个词 打印出来。

下面是当我在Python中用ex25.py模块执行时的样子,如:

Python 2.7.11 (default, May 25 2016, 05:27:56)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] 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

当你搞定每一行代码之后,确保你可以发现在ex25.py中正在运行的方法(function),你要了解每部分的工作方式。 如果你得到不同的结果或错误,你就必须去修正你的代码,退出Python并重新开始。

Study Drills

``

  1. 研究答案中没有分析过的行,找出它们的来龙去脉。确认自己明白了自己使用的是模组 ex25 中\ 定义的函数。
  2. 试着执行 help(ex25)help(ex25.break_words) 。这是你得到模组帮助文档的方式。 所谓帮助文档就是你定义函数时放在 """ 之间的东西,它们也被称作 documentation comments (文档注解),后面你还会看到更多类似的东西。
  3. 重复键入 ex25. 是很烦的一件事情。有一个捷径就是用 from ex25 import * 的方式\ 导入模组。这相当于说:“我要把 ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,\ 开一个新的会话,看看你所有的函数是不是已经在那里了。
  4. 把你脚本里的内容逐行通过 python 编译器执行,看看会是什么样子。你可以执行\ CTRL-D (Windows 下是 CTRL-Z)来关闭编译器。

Common Student Questions

I get None printed out for some of the functions.
You probably have a function that is missing the return at the end. Go backward through the file and confirm that every line is right.
I get -bash: import: command not found when I type import ex25.
Pay attention to what I'm doing in the What You Should See section. I'm doing this in Python not in the Terminal. That means you first run Python.
I get ImportError: No module named ex25.py when I type import ex25.py.
Don't add the .py to the end. Python knows the file ends in .py so you just type import ex25.
I get SyntaxError: invalid syntax when I run this.
That means you have something like a missing ( or " or similar syntax error on that line or above it. Any time you get that error, start at the line it mentions and check that it's right, then go backward checking each line above that.
How can the words.pop function change the words variable?
That's a complicated question, but in this case words is a list, and because of that you can give it commands and it'll retain the results of those commands. This is similar to how files and many other things worked when you were working with them.
When should I print instead of return in a function?
The return from a function gives the line of code that called the function a result. You can think of a function as taking input through its arguments, and returning output through return. The print is completely unrelated to this, and only deals with printing output to the terminal.

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""