def get_word(sentence, n):
# Only proceed if n is positive
if n > 0:
words = sentence.split()
# Only proceed if n is not more than the number of words
if n <= len(words):
return words[n-1]
return (" ")
print(get_word("This is a lesson about lists", 4)) # Should print: lesson
print(get_word("This is a lesson about lists", -4)) # Nothing
print(get_word("Now we are cooking!", 1)) # Should print: Now
print(get_word("Now we are cooking!", 5)) # Nothing
Explanation:
Added parts are highlighted.
If n is greater than 0, split the given sentence using split method and set it to the words.
If n is not more than the number of words, return the (n-1)th index of the words. Since the index starts at 0, (n-1)th index corresponds to the nth word