Hi, I'm taking an online Python class. This is the first time I have used Python. I need Help with an assignment. For the assignment I have to Write a program that counts the number of words and the number of characters of each word in a sentence entered by the user. I can get the input and the word count correct. I need help figuring how to count each individual character in each individual word. The part I need help with the most is the character count variable and loop. I appreciate anyone who helps with this. I'm using Python 3.4.3.

Sentence word and Character counter.py

count the number of words and the number of characters of each word in

a sentence entered by the user

def main():

get the user to enter a sentence

    UserInput = input("Please enter your sentcence.")

    Words = UserInput.split()

WordCount = len(Words[0])
CharacterCount = len(Words[1])


    for Words in UserInput.split():

     WordCount = len(Words[0])
     CharacterCount = len(Words[1])
print("The wordcount is:" , WordCount)
print("The Charactercount is:" , CharacterCount)


3 Years
Discussion Span
Last Post by Brandon500

Here is a hint.

>>> user_input = 'The quick brown fox jumps over a lazy dog'
>>> word_lst = user_input.split()
>>> word_lst
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'a', 'lazy', 'dog']
>>> len(word_lst)
>>> [len(c) for c in word_lst]
[3, 5, 5, 3, 5, 4, 1, 4, 3]
sum([len(c) for c in word_lst])

If you wonder about [len(c) for c in word_lst],so is this called list comprehensions.
list comprehensions is used very much in Python.
To write it in a ordinary loop, it looks like this.

>>> char_count = []
>>> for c in word_lst:
...     char_count.append(len(c))
>>> char_count
[3, 5, 5, 3, 5, 4, 1, 4, 3]

Edited by snippsat


Thank you so much snippsat. I was able to figure everything out. Now the program works how I need it to

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.