A python program that prompts the user to enter a sentence of at least 5 words

A python program that prompts the user to enter a sentence of at least 5 words


sentence = input("Enter a sentence of at least 5 words: ")
words = sentence.split()
while len(words) < 5:
    sentence = input("Please enter a sentence of at least 5 words: ")
    words = sentence.split()

The above code prompts the user to enter a sentence and splits it into individual words. It then checks if the number of words is less than 5. If it is, the user is prompted again until a sentence with at least 5 words is entered.

Solution 1: Using a while loop


sentence = input("Enter a sentence of at least 5 words: ")
while len(sentence.split()) < 5:
    sentence = input("Please enter a sentence of at least 5 words: ")

In this solution, we use a while loop to continuously prompt the user for input until a sentence with at least 5 words is entered. The condition of the while loop checks the length of the sentence after splitting it into words.

Solution 2: Using a for loop


sentence = input("Enter a sentence of at least 5 words: ")
words = sentence.split()
while len(words) < 5:
    sentence = input("Please enter a sentence of at least 5 words: ")
    words = sentence.split()

This solution is similar to the first one, but instead of using a while loop, we use a for loop to iterate over the words in the sentence. The condition of the loop checks if the number of words is less than 5.

Solution 3: Using a recursive function


def get_sentence():
    sentence = input("Enter a sentence of at least 5 words: ")
    words = sentence.split()
    if len(words) < 5:
        return get_sentence()
    else:
        return sentence

sentence = get_sentence()

In this solution, we define a recursive function called get_sentence() that prompts the user for input and checks if the number of words is less than 5. If it is, the function calls itself again until a sentence with at least 5 words is entered. Once a valid sentence is entered, it is assigned to the sentence variable.

Among the three options, Solution 1 using a while loop is the most straightforward and concise. It achieves the desired result without the need for recursion or additional variables. Therefore, Solution 1 is the better option for solving this Python question.

5/5 - (1 vote)

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents