问题
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