#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
You've reached the end of your free preview.
Want to read both pages?
- Fall '19
- susan lee