Invert a String Using a For Loop

Answered using GPT-4o mini by AI Answer Generator

Question:

Program 4: “Invert a String” The intent of this program is to allow a user to enter a string of any length (can be a sentence), and then print the string with the characters in reverse order. Use only a “for loop” to invert the input.

  1. The first output should be a program header as described above like: ########## Program #4 – Invert a String ###########
  2. a prompt to get the user input
  3. a for loop that constructs the inverted string The Output should look something like this: “Hi Bob” is my string and it’s inverted to “boB iH”
Answer:

Here's a simple Python program that inverts a string using a for loop, following the specifications you've provided:

# Program Header
print("########## Program #4 – Invert a String ###########")

# Prompt for user input
user_input = input("Please enter a string: ")

# Initialize an empty string to hold the inverted result
inverted_string = ""

# Use a for loop to construct the inverted string
for i in range(len(user_input) - 1, -1, -1):
    inverted_string += user_input[i]

# Output the result
print(f'"{user_input}" is my string and it’s inverted to "{inverted_string}"')

Explanation:

  1. Program Header: The program starts by printing a header to indicate the program number and purpose.
  2. User Input: It prompts the user to enter a string.
  3. For Loop: The loop iterates over the string in reverse order, starting from the last character to the first, and constructs the inverted string.
  4. Output: Finally, it prints the original string and its inverted version in the specified format.

You can run this code in any Python environment to see how