在Python的“回归功能之外”语法错误原因?(Cause of “return outside o

2019-06-27 23:06发布

我在此代码的问题;

'return' outside function (<module1>, line 4)   <module1>   4

这本书从代码中调用了解蟒蛇硬盘的方式 ; “练习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 storred(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.php(0)
    print word

def sort_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 prinits the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

任何解决方案?

Answer 1:

这个函数的return不正确缩进。

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words


Answer 2:

您缩进了,试试这个:

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

缩进是Python中的一个关键组成部分,其它语言不同 - 所以要确保你的代码是正确的格式是很重要的。



Answer 3:

压痕事项蟒。 从你这里贴上什么最后两行不进行整型break_words的范围。

def break_words(stuff):
    """This function will break up words for us."""
words = stuff.split(' ')
return words


文章来源: Cause of “return outside of function” syntax error in Python?