笨辦法學python 習題25 更多更多練習

2021-10-03 18:28:33 字數 2762 閱讀 8743

原始碼

#命名函式

def break_words(stuff):

"""this function will break up words for us."""

#設定變數words 使用.split()命令分割字串

words = stuff.split(' ')

#返回return words

def sort_words(words):

"""sorts the words."""

#返回 使用sorted()命令公升序排序

return sorted(words)

def print_first_word(words):

"""prints the first word after popping it off."""

#.pop(0)命令刪除並返回第乙個元素

word = words.pop(0)

print(word)

def print_last_word(words):

"""prints the last word after poping it off."""

#.pop(-1)命令刪除並返回最後乙個元素

word = words.pop(-1)

print(word)

def sort_sentence(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自帶shell回顯

python 3.7.3 (v3.7.3:ef4ec6ed12, mar 25 2019, 22:22:05) [msc v.1916 64 bit (amd64)] on win32

>>> import sys

>>> sys.path

['', 'c:\\python37\\lib\\idlelib', 'c:\\python37\\python37.zip', 'c:\\python37\\dlls', 'c:\\python37\\lib', 'c:\\python37', 'c:\\python37\\lib\\site-packages', 'c:\\users\\gw\\test']

>>> 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)

allwait.

>>> ex25.print_first_and_last_sorted(sentence)

allwho

>>>

《笨辦法學python》習題25 筆記

原文習題 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 sorte...

《笨辦法學python》習題38 40

mystuff 然後作者又給出了乙個錯誤的情況 class thing object def test hi print hia thing a.test hello 錯誤原因是test 只可以接受乙個引數,卻給了兩個。也就是 a.test hello 實際上是test a,hello 從這裡開始到...

《笨辦法學Python》 習題3

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 print i will now count my chickens print hens 25 30 6.0 print roosters 100 25 3 4 print now i wil...