I'm a Python beginner and in one of our class exercises we were given a solution that I don't really understand.
The question:
Program that will reverse a string with a loop.
Here is the solution:
string = "Hello World"
s = ""
for ch in string:
s = ch + s
print(s)
I am confused as to why this loop begins at the end of the string. As I understand it the new string should be the same as it will loop from the beginning. Can anyone explain why?
s = s + chbuilds the same string,s = ch + sbuilds the reverse as it prepends the next character.print(s)in the body of the loop and see it printed as it grows. You need to develop ways to answer such questions on your own. The Python shell is good for quick experiments -- so experiment rather than post to Stack Overflow. Only post when your experiments fail to answer the question (which is unlikely to be the case here).