python版本:3.6.1
练习25.更更多练习
练习25的主要操作出现在了power shell里面。
1 def break_words(stuff):
2 """This function will break up words for us."""
3 words = stuff.split(' ')
4 return words
5
6 def sort_words(words):
7 """Sorts the words."""
8 return sorted(words)
9
10 def print_first_word(words):
11 """Prints the first word after popping it off."""
12 word = words.pop(0)
13 print(word)
14
15 def print_last_word(words):
16 """Prints the last word after popping it off."""
17 word = words.pop(-1)
18 print(word)
19
20 def sort_sentence(sentence):
21 """Takes in a full sentence and returns the sorted words
22 words = break_words(sentence)
23 return sort_words(words)
24
25 def print_first_and_last(sentence):
26 """Prints the first and last words of the sentence."""
27 words = break_words(sentence)
28 print_first_word(words)
29 print_last_word(words)
30
31 def print_first_and_last_sorted(sentence):
32 """Sorts the words then prints the first and last one.""
33 words = sort_sentence(sentence)
34 print_first_word(words)
35 print_last_word(words)
这是运行逻辑的代码段,实际上发挥作用的是第3、12、17,这三句,有着功能性的语句split、pop。
与往常一样,其他的代码,名称可以随意改变,不会对实际运行产生影响。
在power shell里面,
1 PS C:\Users\江仞树\lpthw> python
2 Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
3 Type "help", "copyright", "credits" or "license" for more information.
4 >>> import ex25b
5 >>> sentence = "All good things come to those who wait."
6 >>> tom = ex25b.break_words(sentence)
7 >>> tom
8 ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
9 >>> jack = ex25b.sort111111_words(tom)
10 >>> jack
11 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
12 >>> ex25b.print_first_word(tom)
13 All
14 >>> ex25b.print111_last_word(tom)
15 wait.
16 >>> tom
17 ['good', 'things', 'come', 'to', 'those', 'who']
18 >>> ex25b.print_first_word(jack)
19 All
20 >>> ex25b.print111_last_word(jack)
21 who
22 >>> jack
23 ['come', 'good', 'things', 'those', 'to', 'wait.']
24 >>> jack = ex25b.sort_sentence(sentence)
25 >>> jack
26 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
27 >>> ex25b.print_first_and_last(sentence)
28 All
29 wait.
30 >>> ex25b.print_first_and_last_sorted(sentence)
31 All
32 who
我改变了一些变量的名称,但是运行结果没有发生改变。如我前面说的,只要功能性语句没有变动,其他的变量名称无论如何改变,运行结果都不会改变。
然而,有一个变量无法改变名称
1 def sort111111_words(cwords):
2 """Sorts the words."""
3 return sosrted(cwords)
这一部分的第3句,里面的sorted(words),我把这个改为了sosrted(cwords),程序就无法运行了,并不是cwords的改变导致了错误,是sosrted的改变导致了错误的发生。
我前后检查了代码,并没有发现有其他的sorted(words)与其对应,这是一个独立的代码。
我认为这并不是一个功能性的代码,但是却不能随意改变名称,令我十分困惑。