Write a Program That Takes in a Line of Text as Input and Outputs That Line of Text in Reverse. The Program Repeats Ending When The User Enters Done Done Or d For The Line of Text

In this article you will learn a program that keeps accepting a line of text until the user enters “done”, then finally outputs the given line of text in reverse order.

Let's try to solve this using the Python program.

 

Write a Program That Takes in a Line of Text as Input, and Outputs That Line of Text in Reverse. The Program Repeats, Ending When The User Enters Done, Done, Or d For The Line of Text

 

 


Write a Program That Takes in a Line of Text as Input, and Outputs That Line of Text in Reverse. The Program Repeats, Ending When The User Enters Done, Done, Or d For The Line of Text

Let's use an infinite while loop and inside the while loop, take a string variable and ask a user to enter a text.

Once the user enters a text,  check if the text is equal to “done” /”d” If this is true then  print an exit message and break the infinite while loop.

while True:
   text = input("\nEnter a Text : ")
   if text.lower() == "done" or text.lower() == "d":
       print("Exiting the Program Bye !!")
       break
   print("Text in Reverse is... ")
   print(text[::-1])


Outside the if statement reverse the text and print the reverse of a text.  I will be using a string slicing method to reverse a text using [::-1] as shown below.




Python Program
==========================

while True:
   text = input("\nEnter a Text : ")
   if text.lower() == "done" or text.lower() == "d":
       print("Exiting the Program Bye !!")
       break
   print("Text in Reverse is... ")
   print(text[::-1])






Output
===================
Enter a Text : hello world
Text in Reverse is...
dlrow olleh

Enter a Text : i love python
Text in Reverse is...
nohttp evol i

Enter a Text : code with tj
Text in Reverse is...
 jt htiw edoc

Enter a Text : done
Exiting the Program Bye !!




Output
================
Enter a Text : are you busy ?
Text in Reverse is...
? ysub uoy era

Enter a Text : coding !!!
Text in Reverse is...
!!! gnidoc

Enter a Text : d
Exiting the Program Bye !!




Conclusion
=================
In the above Python program we are using an infinite while loop to keep asking a user to enter the text until done is entered.  execute the above Python program by providing random text as input to the program and note down the results.

Comment it down below if you have any suggestions to improve the above my program.




Post a Comment

0 Comments