Python 2.7: a simple implementation for the loop

I am new to programming, and it was difficult for me to understand the logic associated with the Python looping example I came across:

s="abcdefg"
t=""
for a in s:
   t=a+t

I am confused why this piece of code returns "gfedcba". Why should it be otherwise:

s="abcdefg"
t=""
for a in s:
   t=t+a

... which returns "abcdefg".

+4
source share
3 answers

Follow the logic as follows:

s="abcdefg"
t=""

These are the initial variables, now allows you to "expand" the for loop. Keep in mind that “a” means each character “s”, from the first to the last:

t = a + t

so t = "a"

t = a + t

therefore t = "ba"

t = a + t

so t = "cba"

. !

+5

, , a + t t + a .

+ , addition commutative:

>>> "a" + "b"
'ab'
>>> "b" + "a"
'ba'

-

t = a + t

a t,

t = t + a

.

+5

for . , t. a t , s. a t , s

+1

Source: https://habr.com/ru/post/1610125/


All Articles