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


#1



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


Replace this line with your code.


#2

what code do you have so far?


#3

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"

#4

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


#5

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


#6

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


#7

You're right. Thanks


#8

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