I have an assignment to write a code to count words in a string. I haven't learned split yet so I can't use it. I can only use functions, loops and conditionals. He's deliberately added three extra spaces to a string and I have to figure out how to get it to treat it as just one. I'm stuck. Help!
def wordCount(myString):
try:
spaceCount = 0
char = ""
for i in myString:
char += i
if char == " ":
spaceCount == 1
pass
elif char == " ":
spaceCount += 1
return spaceCount+1
except:
return "Not a string"
print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))
try-exceptblocks wrap the smallest amount of code that is possible/useful. And always explicitly catch some error-type, nakedexceptclauses can mask errors you weren't expecting!