M.Sc Python Programming Assignment 10

M.Sc Python Programming Assignments

Assignment 10

Question:

 

Write a program (using functions!) that asks the user for a long string containing multiple 

words. Print back to the user the same string, except with the words in backwards order.

E.g “ I am Msc student”

is :”student Msc am I”

Code:

				
					def reverse_words(string):
    words = string.split()
    reversed_words = words[::-1]
    reversed_string = " ".join(reversed_words)
    return reversed_string

input_string = input("Enter a long string with multiple words: ")

reversed_string = reverse_words(input_string)

print("Reversed string:")
print(reversed_string)

				
			

Output:

				
					Enter a long string with multiple words: He wanted to travel and explore new places, so he saved up money.
Reversed string:
money. up saved he so places, new explore and travel to wanted He

				
			
Tech Amplifier Final Logo