Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Count the number of words in a sentence - Python Program

Example 1 :

sentence = "Python is awesome" print(len(sentence.split()))

Output

 
OUTPUT  :
 3
 

Example 2 :

def count_words(sentence): """ Counts the number of words in a given sentence. Args: sentence: The input string (sentence). Returns: The total number of words in the sentence. """ words = sentence.split() # Splits the sentence into a list of words by whitespace. return len(words) # Returns the length of the list, which is the word count. # Example usage input_sentence = input("Enter a String : ") word_count = count_words(input_sentence) print(f"The sentence is: \"{input_sentence}\"") print(f"The number of words in the sentence is: {word_count}")

Output

 
OUTPUT  :
Enter a String : Did you know, Python is fun
The sentence is: "Did you know, Python is fun"
The number of words in the sentence is: 6