def reverse_string(s):
return s[::-1]
input_string = input("Enter a string: ")
reversed_string = reverse_string(input_string)
print("Reversed string:", reversed_string)
#source code --> clcoding.com
Code Explanation:
def reverse_string(s):
return s[::-1]
This defines a function named reverse_string that takes one parameter, s (a string).
s[::-1]: This uses Python's slicing syntax to reverse the string:
s[start:end:step]: A slice of the string s is created with the given start, end, and step values.
:: without specifying start and end means to consider the entire string.
-1 as the step value means to traverse the string from the end to the beginning, effectively reversing it.
The reversed string is then returned by the function.
Getting User Input
input_string = input("Enter a string: ")
This prompts the user to enter a string.
The entered string is stored in the variable input_string.
Calling the Function
reversed_string = reverse_string(input_string)
The reverse_string function is called with input_string as the argument.
The reversed version of the string is returned by the function and stored in the variable reversed_string.
Printing the Result
print("Reversed string:", reversed_string)
This prints the reversed string to the console with the label "Reversed string:".
0 Comments:
Post a Comment