Introduction:
The provided Python program is designed to take a user input sentence, process it, and then print out the words from the input sentence that have an even length. An even-length word is a word that contains an even number of characters.
Algorithm:
1. Define a function named print_even_length_words that takes an input_string as an argument.
2. Within the function, split the input_string into individual words using the split() method. This creates a list of words.
3. Iterate through each word in the list of words using a for loop.
4. Inside the loop, check the length of the current word using the len() function.
5. Use the modulo operator % to determine if the length of the word is even (i.e., if len(word) % 2 == 0).
6. If the length of the word is even, print the word using the print() function.
7. After defining the function, prompt the user to enter a sentence using the input() function and store it in the variable user_input.
8. Display the message “Even length words:” to indicate that the program is about to print even-length words.
9. Call the print_even_length_words() function, passing user_input as an argument, which will print the even-length words from the user’s input sentence.
Python Code :
def print_even_length_words(input_string):
words = input_string.split()
for word in words:
if len(word) % 2 == 0:
print(word)
user_input = input("Enter a sentence: ")
print("Even length words:")
print_even_length_words(user_input)
Input :
Enter a sentence: systech computer education
Out put :
Even length words:
computer
Explanation:
- The program starts by defining a function named print_even_length_words that takes an input_string This function is responsible for processing and printing even-length words.
- Inside the function, the input_string is split into individual words using the split() method, which separates words based on spaces. This creates a list of words.
- The program then enters a loop that iterates through each word in the list of words.
- For each word in the loop, the len() function is used to calculate the length of the word (i.e., the number of characters in the word).
- The program checks if the length of the word is even by using the modulo operator %. If the remainder of len(word) % 2 is equal to 0, then the word has an even length.
- If the word has an even length, it is printed using the print()
- Outside of the function definition, the program prompts the user to input a sentence using the input() function and stores the input in the variable user_input.
- The program displays the message “Even length words:” to provide context for the output that follows.
- The print_even_length_words() function is called with user_input as an argument, causing it to process the input sentence and print out the even-length words.
In summary, this program takes user input, identifies even-length words in the input sentence, and prints them to the console.