How can i do this using function conditionals and loops please?

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

I need a breakdown of the steps to determine the number of words in “He is back”. Mind the fact that there are double spacing but the code should count as one. Thanks

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>

```python

Replace this line with your code.

<do not remove the three backticks above>

what code do you have so far?

def word_count(mystring):

try:
    temp = 0
    count = 1
    for char in mystring:
        if char == " ":
            temp += 1
            if temp == 1:
                count += 1
            elif temp == 0:
                pass

    return count
except:
    return "Not a string"

this seems to work fine, what is the problem/question?

It’s supposed to count 4 for this string “Four words are here!” but it is counting 2.

look at this code:

def word_count(mystring):

  try:
    temp = 0
    count = 1
    for char in mystring:
        if char == " ":
            print temp
            temp += 1
            if temp == 1:
                count += 1

    return count
  except:
    return "Not a string"

print word_count("Four words are here, even more words!")

temp will just keep increasing (as you can see), so if temp == 1: is only true once, you will need a way to set back temp to zero, which is pretty simple, if char == " ": increase word count, else set temp back to zero. That seems to do the trick

You’re right. Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.