Question:
Python help with loops?
Live Laugh Love
2013-06-22 22:01:31 UTC
I am supposed to reverse a string like Python! to !nohtyP.

I was wondering why my block of code isn't working?

def reverse(text):
i = len(text) - 1
for j in text:
while i >= 0:
j = text[i]
return j
i -= 1
Three answers:
Russel
2013-06-23 04:28:10 UTC
In future posts on Y!A please replace one tab with 4 dots to preserve indentation for Python code.



I have to say your code even with indentation would look like gibberish. It just doesn't make sense. You have what looks like a while loop nested inside a for loop. In the for loop your iterating through the character of the text argument by assigning them to j but in the while loop your assigning to j via text[i]. Then you're returning j just before decrementing i. It looks like two separate failed attempts fused together into some kinda hybrid mishap. It's almost scary.



def reverse(text):

....result = ''

....for x in range(len(text)-1, -1, -1): # the usual range semantics to go in reverse

........result += text[x]

....return result



But say you didn't have the step argument in range. Simple arithmetic would do.



def reverse(text):

....result = ''

....for x in range(len(text)):

........result += text[len(text) - 1 - x]

....return result



Or if you're still getting used to for loop, a while loop could do.



def reverse(text):

....result = ''

....x = len(text) - 1

....while x >= 0:

........result += text[x]

........x -= 1

....return result



and ofcourse as has already been pointed out



def reverse(text):

....return text[::-1]
lawrence
2017-01-22 17:44:23 UTC
1
Shim
2013-06-23 00:46:27 UTC
something like



s = 'shim'

s = s[::-1]

print s


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...