0

I trying to get into programming and have a simple question:

If I have

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = break_words(sentence)
    words = sorted(words)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

When I run it, my code is fine, while if I write

####################Test################

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = break_words(sentence)
    words = sort_words(words)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

I will get

AttributeError: "list" object has no attribute "split"

both functions break_words and sort_words create list objects, so why do I get the error in my second case?

2 Answers 2

2

print_first_word(sentence) calls

words = break_words(sentence)

Here, words is a list now, then it's passed to sort_words(words), and next break_words(words), in which calls

words = stuff.split(' ')

where stuff is a list, causing the error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! this was very helpful
0

I think that the second source code should be:

####################Test################

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = sort_words(sentence)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

I changed words = sort_words(words) to words = sort_words(sentence)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.