Dremendo Tag Line

Input a sentence and print the longest word in Python

String Methods - Question 8

In this question, we will see how to to input a sentence and print the longest word in Python programming. To know more about string methods click on the string methods lesson.

Q8) Write a program in Python to input a sentence and print the longest word.

Program

w=""
lw=""
str=input("Enter a sentence\n")
str=str+" "

for i in range(0,len(str)):
    if str[i]!=' ':
        w=w+str[i]
    else:
        if len(w)>len(lw):
            lw=w
        w=""

print('Longest word =',lw)

Output

Enter a sentence
I am learning to code in Python
Longest word = learning
video-poster