String Methods :Review, part 10

link: https://www.codecademy.com/courses/learn-python-3/lessons/string-methods/exercises/review-ii

For the last part, I don’t understand why my answer is wrong, i have iterated every variable in titles and poets and dates, but my output is only one sentence “The poem Dreamwood was published by Adrienne Rich in 1987.”

def poems(titles,poets,dates):
for title in titles:
for poet in poets:
for date in dates:
msg=“The poem {title} was published by {poet} in {date}.”.format(title=title,poet=poet,date=date)
return msg
print(poems(titles,poets,dates))

Output: The poem Dreamwood was published by Adrienne Rich in 1987.

It looks like you had a function to return a string, but you didn’t print all of the strings that it wanted.
Also, the nested loops will redo the string in msg many times, and will then return whatever msg was last.

That loop will go through every title in titles, and for every title, it will go through every poet in poets, and for every poet, it will go through every date in dates
… which would be
length of title × length of poets × length of dates
number of iterations;
(meaning you would be doing every combination of author, poet, and date of publication).

I didn’t use nested loops (and I didn’t create a function) for that one.

length = len(titles)
poem_info = "The poem {} was published by {} in {}."
for i in range(length):
  print(poem_info.format(titles[i], poets[i], dates[i]))

Or you could do it without using indices:

poem_info = "The poem {} was published by {} in {}."
# highlighted_poems_details is a list of lists that are [title, author, date]
for info in highlighted_poems_details:
  print(poem_info.format(info[0], info[1], info[2]))
1 Like