F.E. PPS Unit 3 Practical 10 solution

Practical 10: Program that takes a string as input and reverses it using a user-defined function.

Problem Statement

Write a Python program that takes a string as input and reverses it using a user-defined function.

Solution Code

				
					# Function to reverse a string
def reverse_string(s):
    reversed_s = ""  # Initialize an empty string
    for char in s:
        reversed_s = char + reversed_s  # Add each character to the beginning
    return reversed_s

# Taking input from the user
string = input("Enter a string: ")

# Calling the function and displaying the result
reversed_string = reverse_string(string)
print("Reversed String:", reversed_string)

				
			

Expected Outcome

  • The program takes a string as input from the user.
  • It uses a user-defined function to reverse the string.
  • The reversed string is then displayed as output.

Example output:

				
					Enter a string: Engineering
Reversed String: gnireenignE
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 3 Practical 10 solution where we have written Python program that takes a string as input and reverses it using a user-defined function.

  1. Defining the Function reverse_string(s):
    • An empty string reversed_s is initialized.
    • A for loop iterates through each character of the input string.
    • Each character is added to the beginning of reversed_s, effectively reversing the string.
    • The function returns the reversed string.
  2. Taking User Input:
    • The user enters a string.
  3. Calling the Function and Printing the Output:
    • The input string is passed to reverse_string() for processing.
    • The reversed string is printed.

Key Concepts Learned

  • User-Defined Functions:
    • Creating and calling a function in Python.
  • String Manipulation:
    • Reversing a string without using built-in functions like [::-1] or reversed().
  • Looping Through a String:
    • Using a for loop to iterate through characters.
Tech Amplifier Final Logo