首页 > 解决方案 > 在 python ex25.py 中得到不同的输出。来自Learn python the hardway.python 3.6

问题描述

ex25.py

def break_words(stuff):
    """This function will break up words for us ."""
    words = stuff.split(' ')   # words = stuff.split('') prevents from running the program.
    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):
    """Print the last word after popping it off."""
    word = words.pop(-1)
    print(word)


def sort_sentence(sentence):
    """Take 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):
    """Sort the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

imported to ex25 session.py

import ex25
sentence = "All good things come to those who waite."
words = ex25.break_words(sentence)# the space in "words = stuff.split('')" stoped the program from running.
words
sorted_words = ex25.sort_words(words)
sorted_words
ex25.print_first_word(words)
ex25.print_first_word(words)
words
ex25.print_first_word(sorted_words)
ex25.print_last_word(sorted_words)
sorted_words
sorted_words = ex25.sort_words(sentence)
sorted_words
ex25.print_first_and_last(sentence)
ex25.print_first_and_last_sorted(sentence)

运行输出如下!

All
good
All
who
All
waite.
All

我试图分解代码并将其分成几部分。我在任何地方都找到了(中断和排序函数,程序跳过了它们!。通知一下,我使用的是 pycharm python 3.7。

标签: pythonpython-3.x

解决方案


推荐阅读