笨办法学Python3 习题25 更多更多的训练

发布时间 2023-10-06 23:49:13作者: 萹豆

练习内容:

  • 将ex25模块导入
  • 在终端中手动运行函数
  • 查看变化结果
  • 退出quit()
 1 def break_words(stuff):
 2     "用来分割参数元素"
 3     words = stuff.split(' ')
 4     return words
 5 
 6 def sort_words(words):
 7     "用来将参数元素升序排列"
 8     return sorted(words)
 9 
10 def print_first_word(words):
11     "将第一个元素传递并删除"
12     word = words.pop(0)
13     print(word)
14 
15 def print_last_word(words):
16     "最后一个元素传递并删除"
17     word = words.pop(-1)
18     print(word)
19 
20 def sort_sentence(sentence):
21     "分割并升序排序,将函数1和函数2功能置入函数5中合并"
22     words = break_words(sentence)
23     return sort_words(words)    
24 
25 def print_first_and_last(sentence):
26     "先分割,再传递第一个和最后一个元素,用到函数1,函数3,函数4"
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     "先分割排序,再传递第一个和最后一个元素,用到函数5,函数6,函数7"   
33     words = sort_sentence(sentence)
34     print_first_word(words)
35     print_last_word(words)
PS C:\Users\Administrator\lpthw> python
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
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.']
>>> ex25.sort_words(words)
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'who']
>>> quit()