HRS - Ask. Learn. Share Knowledge. Logo

In Computers and Technology / High School | 2025-07-08

Construct a program which accepts a sequence of words separated by whitespace as input. Print words composed of digits only. def print_digit_words(filename):

Asked by QveenMiracle7979

Answer (1)

To construct a program that accepts a sequence of words and prints only those words composed entirely of digits, we can write a function in Python.
Here's a step-by-step guide:

Define the Function: Start by defining a function named print_digit_words().

Accept Input: Use Python's input() function to receive a sequence of words from the user. Words should be separated by whitespace (spaces, tabs, or newlines).

Split the Input: Use the .split() method on the input string to break it into individual words based on whitespace. This will return a list of words.

Filter Digit Words: Iterate over this list of words.

For each word, use the .isdigit() method to check if the word is composed entirely of digits.


Print the Digit Words: If a word is composed of digits only, print it.


Here is a sample implementation in Python:
Define the function
def print_digit_words(): # Accept input words from the user input_string = input("Enter a sequence of words separated by whitespace: ") # Split the input string into individual words words = input_string.split() # Iterate over the words to find those composed of digits for word in words: # Check if the word is composed only of digits if word.isdigit(): print(word)
Call the function to execute it
print_digit_words() ;

Answered by danjohnbrain | 2025-07-22