Write a Program to Take a Sentence as Input And Display The Longest Word in The Given Sentence

Hi, in this article you will learn a Python program to take a sentence as a Input and display the longest word present in the Sentence . Let's use the following to iterate all the words present in the sentence and then check the longest word using the if statement.

Let's try to solve this using the python script

 

Write a Program to Take a Sentence as Input And Display The Longest Word in The Given Sentence




Write a Program to Take a Sentence as Input And Display The Longest Word in The Given Sentence

Take a sentence variable and ask the user to enter a sentence using the input function call,  take another variable named as longest and initialize it to an empty string.  The longest variable  will store the longest word present in the sentence.

sentence = input("Enter a Sentence : ")
longest = ""




Now use the for loop to iterate all the words present in the sentence using the split function call. Use the if statement to compare if the given word is greater than the longest then swap the longest with the given word.

Once the for loop completes you will be having the longest word stored in the longest variable as shown below.

for word in sentence.split():
   if len(word) > len(longest):
       longest = word



Use the print function call to print the longest word present in the sentence.

print("Longest word in sentence is : ",longest)



Complete Python Program
===============================

sentence = input("Enter a Sentence : ")
longest = ""

for word in sentence.split():
   if len(word) > len(longest):
       longest = word

print("Longest word in sentence is : ",longest)




Output 1
===========

Enter a Sentence : Write a Program to Take a Sentence as Input And Display The Longest Word in The Given Sentence
Longest word in sentence is :  Sentence



Output 2
===============

Enter a Sentence : code with tj
Longest word in sentence is :  code



Output 3
==============

Enter a Sentence : let's go watch a movies
Longest word in sentence is :  movies



Output 4
===========

Enter a Sentence : complete your assignments and then you can use your play station
Longest word in sentence is :  assignments




Conclusion
=================

The above Python program uses the input function call to accept the user input,  then it uses a for loop and if statement to get the longest word present in the sentence.  Finally, the program used the print function call to print the longest word present in the sentence.

Execute the above Python program using the latest version of python.  provide the random  sentence as an input to the Python program and not down the  longest word.

Comment it  down below  if you have any  queries regarding the above Python program


Post a Comment

0 Comments