def reverse_words(sentence):
# Split the sentence into a list of words
words = sentence.split()
# Initialize an empty list to store the reversed words
reversed_words = []
# Loop through the words backwards and append each to the reversed_words list
for i in range(len(words) - 1, -1, -1):
reversed_words.append(words[i])
# Join the reversed words into a single string with spaces
reversed_sentence = ' '.join(reversed_words)
return reversed_sentence
# Example usage
input_sentence_1 = "Hello world"
output_sentence_1 = reverse_words(input_sentence_1)
print(output_sentence_1) # Output: "world Hello"
input_sentence_2 = "Keep calm and code on"
output_sentence_2 = reverse_words(input_sentence_2)
print(output_sentence_2) # Output: "on code and calm Keep"
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter