1

I am trying to create a program in Python which takes any entered word and reverses the order, and prints the word in the reverse order. But I am not getting the desired results. Here is the code I am using:

myString = input("Enter any String: ")
length = len(myString)-1
reverse = []
i = 0
while length>=0:
    reverse.append(myString[length])
    length -=1

while length<0:
    break
print(reverse)
reverseString = ''
j = 0
while j<=length:
    reverseString +=reverse[j]
    j+=1
while j> length:
    break
print(reverseString)

In the output, I only see this:

Enter any String: De Costa
['a', 't', 's', 'o', 'C', ' ', 'e', 'D']

and not this as expected: 'atsoC eD'

Where am I going wrong?

srini
  • 201
  • 2
  • 11

3 Answers3

1

This is because your length variable becomes 0 since you decrement it in the first loop, hence the loop for reverseString never runs, so reverseString always has the value '', you have to reinitialize the length variable so that the loop runs. To do so add length = len(myString)-1 below reverseString = ''

or simply, this

myString = input("Enter any String: ")
length = len(myString)-1
reverse = []
i = 0

while length>=0:
    reverse.append(myString[length])
    length -=1

while length<0:
    break
print(reverse)

reverseString = ''
length = len(myString)-1

j = 0
while j<=length:
    reverseString +=reverse[j]
    j+=1
while j> length:
    break
print(reverseString)
Imtinan Azhar
  • 1,725
  • 10
  • 26
0
# using loop
def reverse(s):
  str = ""
  for i in s:
    str = i + str
  return str

print (reverse("Hello World")) # dlroW olleH

# using recursion
def reverse1(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]

print (reverse1("Hello World")) # dlroW olleH

# using extended slice syntax
def reverse2(string):
    string = string[::-1]
    return string

print (reverse2("Hello World")) # dlroW olleH


# using reversed()
def reverse3(string):
    string = "".join(reversed(string))
    return string

print (reverse3("Hello World")) # dlroW olleH
ncica
  • 7,015
  • 1
  • 15
  • 37
0

You can use index slicing.. i think below code is useful.

myString = input("Enter any String: ")
reverse = ""
reverse = myString[::-1]