startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
endmsg=startmsg[i] + endmsg
print(endmsg)
Why is the result: "olleh", a not "hello"?
>Solution :
As this code iterates, it adds each letter to the front of what’s been iterated over previously. The end result is a reversed string.
As we iterate:
endmsg = "h"
endmsg = "eh"
endmsg = "leh"
endmsg = "lleh"
endmsg = "olleh"
Iterating over indexes like this is not particularly idiomatic Python. Rather, if the index is not needed, it would be more Pythonic to iterate over the characters directly.
startmsg = "hello"
endmsg = ""
for ch in startmsg:
endmsg = ch + endmsg
print(endmsg)