Dremendo Tag Line

Input sentence and count the number of words in it in Python

String Methods - Question 2

In this question, we will see how to input a sentence and count the number of words in it in Python programming. To know more about string methods click on the string methods lesson.

Q2) Write a program in Python to input a sentence and count the number of words in it. Assume that there may be any number of blank spaces between the words.

Program

wc=0
str=input('Enter a sentence\n')

for i in range(0,len(str)):
    if i==0 and str[i]!=' ':
        wc=wc+1

    elif str[i]==' ' and str[i+1]!=' ':
        wc=wc+1

print('Total words =',wc)

Output

Enter a sentence
We are    free to  take  our    own decision
Total words = 8
video-poster