Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Make a file poem.txt with the three lines roses are red, violets are blue and sugar is sweet. Read it, and show the number of lines, the number of words, and the longest word.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Loop over the lines, split each line into words, and count. Keep the longest word so far.
Check. 3 lines. Words: 3 + 3 + 3 = 9. The longest word is violets with 7 letters (sugar has 5 and sweet has 5).
Answer: 3 9 violets.
Log in to join the discussion.
Loading…