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])
loop
    for Words in UserInput.split():


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

main()

Recommended Answers

All 2 Replies

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)
9
>>> [len(c) for c in word_lst]
[3, 5, 5, 3, 5, 4, 1, 4, 3]
sum([len(c) for c in word_lst])
33

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]

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.