Question 2 of 6intermediate🔧 ApplyLong Answer5 marks

Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), total number of alphabets, total number of digits, total number of special symbols and total number of words in the given text. (Assume that each word is separated by one space).

Correct Answer

python

Program to count characters, alphabets, digits, special symbols and words

text = input("Enter a line of text: ")

Initialize counters

total_chars = len(text) alphabets = 0 digits = 0 spaces = 0 special_symbols = 0

Count each type of character

for char in text: if char.isalpha(): alphabets += 1 elif char.isdigit(): digits += 1 elif char.isspace(): spaces += 1 else: special_symbols += 1

Count words (words separated by space)

words = len(text.split())

Display results

print("Total number of characters:", total_chars) print("Total number of alphabets:", alphabets) print("Total number of digits:", digits) print("Total number of special symbols:", special_symbols) print("Total number of words:", words)

Explanation: The program takes a line of text as input from the user. The len() function calculates the total number of characters including white spaces.

A for loop iterates through each character in the text. The isalpha() method checks if the character is an alphabet, isdigit() checks for digits, and isspace() identifies white spaces. Characters that don't fall into these categories are counted as special symbols.

The split() method splits the text into a list of words based on spaces, and len() gives the word count. This approach efficiently categorizes all characters and provides the required counts.

Exercise: PROGRAMMING PROBLEMS | Q: 1 | (Page 14)
For More Understanding

Explanation

This program uses string methods covered in the NCERT textbook. The isalpha(), isdigit(), and isspace() methods are standard string methods for character classification. The split() method is mentioned in the context for splitting strings. The for loop structure follows Program 8-1 from the textbook which demonstrates iterating through characters in a string.

Solution Steps

  1. Step 1: Accept input text from user using input() function

  2. Step 2: Calculate total characters using len() function

  3. Step 3: Initialize counters for alphabets, digits, spaces and special symbols to zero

  4. Step 4: Iterate through each character using for loop and classify using isalpha(), isdigit(), isspace()

  5. Step 5: Count words by splitting text using split() and applying len() on the resulting list

  6. Step 6: Display all the counts using print statements