Cause of “return outside of function” syntax error in Python?

柔情痞子 提交于 2019-12-04 04:46:16

问题


I have problem in this code;

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

This code from book called Learn the python hard way; "Exercise 25: Even More Practice"

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)

any solutions ?


回答1:


in this function the return is not properly indented.

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



回答2:


Your indentation is off, try this:

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

Indentation is a key component of Python, unlike some other languages - so it is important to ensure that your code is properly formatted.




回答3:


Indentation matters in python. From what you've pasted the last two lines here are NOT int the scope of break_words.

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


来源:https://stackoverflow.com/questions/12307369/cause-of-return-outside-of-function-syntax-error-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!