FAQ: Learn Python - Practice Makes Perfect - reverse

As shown in staffsar’s response, in the solution, it first converted

l = len(text) - 1
while l >= 0:
word = word + text[l]
l -= 1

In my solution, I tried to use

while len(text) >= 1:
word = word + text[len(text) - 1]
len(text) = len(text) - 1

but I get “SyntaxError: can’t assign to function call”

My question is: why doesn’t len(text) = len(text) - 1 work?

Pretty much says it all. If we wish to add to length, then we must add to the list. The len() function evaluates the length of list and returns a value. Something that returns a value cannot be assigned to, but assigned to something.

The string “Hello world” is 11 characters long (including the space). Since our condition is while l >= 0, for the loop to end at l = 0, we need (10 to 0) eleven subtractions, with initial value l =10.

Help Please!
What’s wrong with my “while”?
My idea was to create a list using “while”
So I start with list =
and add numbers
so it’s list=[5,4,3,2,1,0]
But my “while” stops after list=[5]

def reverse(text):
  while x > 0:
    for n in list_:
      print text[n],

Remove all other code than what you’re specifically looking at so that there’s less going on.

A while-loop continues for as long as the condition is met. What variables are used in the condition, what values do they have? That’s something you can print out and look at.

To post code on a forum you’ll need to tell the forum not to apply regular text formatting rules, to leave it alone. There are a couple of buttons in the editor, one of them is for that.

It looks a bit as if though you’ve got while-else in your code. What does that do? I expect you don’t know, but you should be aware of that you don’t know that - because you can’t possibly leverage it if you don’t know what it does. You need to be super deliberate about everything you write.

I would expect that as long as “while” condition is met , so x>0 (should be x>=0) “while” will be repeating the sequence and move to else when x<0

also, is your observation about it stopping correct?


maybe it was, and you just expressed this a bit weirdly:

when it was that 0 wasn’t added, and changing the condition to >= would indeed include that