[Tutor] doubt in a program
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Jan 29 04:25:52 EST 2018
On 29/01/18 06:42, vinod bhaskaran wrote:
> newstring = ''
> oldstring = 'Newton'
> for char in oldstring:
> newstring = char + newstring
> print(newstring)
>
> Could someone explain how it is traversing to get the string reversed?
print statements are your friend.
Add print statements everywhere that a variable changes value:
newstring = ''
oldstring = 'Newton'
for char in oldstring:
print ("char=",char)
newstring = char + newstring
print(newstring=",newstring)
print(newstring)
That will let you see how the newstring gets built
up inside the loop.
You could do the same thing using a paper and pen,
just walk through the code in your mind and write
down the values each time, like so:
char newstring
N N
e e = N -> eN
w w + eN -> weN
etc...
> As the new character is adding the char in the new string but how is it
> getting reversed without any line giving the char number to be traversed in
> reverse order.
As you will see if you do either of the suggested
exercises the addition always puts the latest char
at the front of the newstring.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list