Trying to count the number of words from user input

880 views python
-4

I'm currently trying to count the amount of words in a sentence entered by the user and count the amount of times the word 'Python' is used in the sentence and print both the results at the end. I'm trying to force the sentence into lowercase but I'm currently unsure how to integrate it into the code. As of now it counts the amount of times 'Python' was entered but not 'python' and I need both to be registered at once.

sentence = input(str("Please enter a sentence with your thoughts on Python:"))
listOfWords = len(sentence.split())
howManyPython = sentence.count (str("Python" or "python"))
print("You said Python " + str(howManyPython) + " times!")
print("There was " + str(listOfWords), "words in your sentence")

answered question

What do you think "Python" or "python" is? Unsure? Then Try it...

please check my answer

2 Answers

6

Convert entire input sentence to lower case first,

sentence = input(str("Please enter a sentence with your thoughts on Python:"))
howManyPython = sentence.lower().count ("python")
listOfWords = len(sentence.split())
print("You said Python " + str(howManyPython) + " times!")
print("There was " + str(listOfWords), "words in your sentence")

# output
Please enter a sentence with your thoughts on Python:python 123 Python Python
You said Python 3 times!
There was 4 words in your sentence

posted this
8

You can convert to whole input string to lowercase, to count the word 'Python':

sentence = 'Python python python3000 py'
listOfWords = len(sentence.split())
howManyPython = sentence.lower().count("python")  # convert to lowercase
print("You said Python " + str(howManyPython) + " times!")
print("There was " + str(listOfWords) + " words in your sentence")

Returns:

You said Python 3 times!
There was 4 words in your sentence

posted this

Have an answer?

JD

Please login first before posting an answer.