0

prompts the user to enter a sentence of at least 5 words. Include a test to ensure that the user has entered at least 5 words. Store the individual words as separate items in a list. Print the sentence in reverse order - word by word. The words must print in one line (not beneath each other). Insert spaces between the words. Example: "What is the best song right now" > "now right song best the is What" Print the sentence in reverse order - letter by letter. The words must print in one line (not beneath each other). Insert spaces between the words. # Example: "What is the best song right now" > "won thgir gnos tseb eht si tahW

This is what I have so far

Sentence = input(("Enter a sentence: "))
Word = Sentence.split(" ")
reverse_words[::-1]
length = len(words)
if length!=5:
    print("Error! Please enter only 5 words")
else:
    print(length)
    print(" ".join(reverse_words))
Francis
  • 1
  • 2

2 Answers2

0
def reverse_sentence(sentence):
     sentence_list = sentence.split(" ")
     if(len(sentence_list ) < 5):
             print("Please, insert a sentence with at least 5 words")
             return
     print(" ".join(sentence_list[::-1]))
     print(sentence[::-1])

This will print both desired outputs:

sentence = "What is the best song right now"
reverse_sentence(sentence) # "now right song best the is What"
                           # "won thgir gnos tseb eht si tahW"
Samuel
  • 378
  • 1
  • 9
-1

You can reverse a string with the function reversed:

s='word'
for letter in reversed(s):
    print(letter, end="")

output:

drow

Similarly, a list can be reversed:

for i in reversed(list(range(0,4))):
    print(i, end="")

output:

3210
JoKing
  • 430
  • 3
  • 11
  • `range` doesn't produce a `list` in Python 3 (it's a dedicated sequence type of its own, with fixed memory overhead regardless of length). `reversed` just works on arbitrary sequences (plus anything else that defines an ordering, e.g. `dict`s in the most modern Python versions), producing an iterator that runs in reverse. – ShadowRanger Jun 17 '20 at 00:25
  • and that helps OP how? – JoKing Jun 17 '20 at 17:53