3.5.7 WordLength sample answer.py - #As before there are lots of ways to do this We'll cover#one that can be done using only what we've covered so

3.5.7 WordLength sample answer.py - #As before there are...

This preview shows page 1 - 2 out of 2 pages.

#As before, there are lots of ways to do this. We'll cover #one that can be done using only what we've covered so far, #but there are other ways to do this. # #First, we start with the function header: def average_word_length(my_string): #And as before, we wrap everything in a try block so #that we can react to errors that arise: try: #Average word length is the number of characters #divided by the number of words. So, we know we're #going to need to count both of those things: word_count = 0 letter_count = 0 #And we're going to need to reuse the method we used #before to avoid consecutive spaces. Notice, though, #that this problem says not to assume the string #starts with a letter. How can we take care of that? #Here, we're going to redefine how we identify words: #a new word starts when a letter occurs after a #space. So, let's pretend like a space occurred right #before the string started: previous_was_space = True #This way, if the first character in the string is a #letter, it's counted as a new word because it #"follows" the space. If it's not, it won't count
Image of page 1
Image of page 2

You've reached the end of your free preview.

Want to read both pages?

  • Fall '19
  • susan lee

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes