Working my way through Learn Python the Hard Way ex.25, and I just can’t wrap my head around something. Here’s the script:
def break_words(stuff):
"""this function will break waords up for us."""
words = stuff.split(' ')
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):
"""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 prints the first and last ones."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
When running the script, break_words will use any argument I create if I use the command break_words(**). So I can type
sentence = "My balogna has a first name, it's O-S-C-A-R"
and then run break_words(sentence) and end up with a parsed “‘My’ ‘balogna’ ‘has’ (…).
But other functions (like sort_words) will only accept a function with the name “words.” I must type
words = break_words(sentence)
or something for sort_words to work.
Why can I pass any argument in the parentheses for break_words, but only arguments that are actually attributed to “sentence” and “words” specifically for sort_words, print_first_and_last, etc.? I feel like this is something fundamental that I should understand before I move on in the book, and I just can’t get my head around it.
It’s about the type of value that each function accepts as its parameter.
break_words returns a list. sort_words uses the built-in function sorted(), which expects to be passed a list. This means that the parameter you pass to sort_words should be a list.
Maybe the following example illustrates this:
Note that python defaults to being helpful even though this can at times be confusing. So if you pass a string to sorted(), it will treat it as a list of characters.