I made a word counter. It works as long as there aren't any lone punctuation marks. How could it be improved? (Could it be made simpler? Are the comments detailed/clear enough? etc.) I know it's simple, but I don't want to develop bad habits early on.
#prompt user to input a sentence toCount = raw_input("--- ") #function that counts words of inputted sentence def countWords(theString): stringLength = len(theString) #index for each character in string counter1 = 0 #stores word count accumulator = 0 #go through each character in input text. if a character is a space #with no preceding spaces, add 1 to word count. while counter1 < stringLength: stringChar = theString[counter1] if stringChar == ' ' and counter1 > 0 and theString[counter1 - 1] != ' ': accumulator = accumulator + 1 counter1 = counter1 + 1 else: counter1 = counter1 + 1 #if last character in input text is not a space, add 1 to word count if theString[counter1 - 1] != ' ': accumulator = accumulator + 1 output = "You typed " + str(accumulator) + " words." return output print countWords(toCount)