0

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 "Quit", "quit", or "q" for the line of text.

Ex: If the input is:

Hello there

Hey

quit

then the output is:

ereht olleH

yeH

''' I am having trouble with this problem and my teacher has not been able to explain things well at all. I have been able to print out one input in reverse, but I am not sure how to print out all of them and break the loop with a 'q', 'quit', or 'Quit'. Please help.

My code so far:

mystring = str(input())

myreverse = ''

for i in mystring:
    myreverse= i+ myreverse
print(myreverse)
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51

2 Answers2

1

Well done. You were very close. Learning can be challenging if the teacher is not good but with determination and effort, you will definitely become good at python. Keep up the good work.

Let me first help you fix up your code and then I will suggest an improvement.

while True:
    mystring = str(input())
    if mystring == 'Quit' or mystring == 'quit' or mystring == 'q':
        break
    myreverse = ''
    for i in mystring:
        myreverse= i+ myreverse
    print(myreverse)

Here's what I have done to fix the code:

  • Put your existing code inside a while True: loop so that it runs forever.
  • Put a if statement that checks for Quit, quit and q inputs.

Here is an improved version of the above code:

while True:
    my_string = str(input())
    if my_string in ['q', 'quit', 'Quit']:
        exit()
    print(my_string[::-1])

Here is the explanation for how the above code works:

  • while True makes the program run forever
  • The if statement checks whether the user entered Quit, quit or q.
  • exit() closes the program
  • my_string[::-1] reverses the string. This eliminates the need to have the for loop to reverse the string.
theQuestionMan
  • 1,270
  • 2
  • 18
  • 29
0

Was a loop like this what you were trying to achieve?

exit = False
while not exit:
  phrase = str(input("Type something (exit = q or quit): "))

  if phrase.lower() == 'q' or phrase.lower() == 'quit':
    exit = True
    break
  else:
    myreverse = ''

    for element in phrase:
        myreverse= element + myreverse

    print("Reversed = %s\n" % myreverse)
BWallDev
  • 345
  • 3
  • 13