Home > database >  I do not understand why this function reverses the string
I do not understand why this function reverses the string

Time:10-06

This function requests a string input and reverses it. For some reason, I just cannot wrap my head around the logic behind it.

def reverse(s):
    new = ""
    for i in s:
        print(new)
        new = i   new
    return new

oldStr = input("String?")
newStr = reverse(oldStr)
print(newStr)
print(reverse("good bye"))

A friend suggested I print the variable new in the string which I added and it helped a little, but I just don't understand it.

CodePudding user response:

Let analysis it: Iteration 1: new = 'A', i = g

Perform new = i new : new = gA

Iteration 2: new = gA, i = o

Perform new = i new: new = ogA . . .

This happens because we add new i before we add the existing string from previous iteration.

CodePudding user response:

the key is in "new = i new" note that new is the previous iteration character and is in the right side of the current character, this cause the string to reverse

CodePudding user response:

It looks to me as if you are in a stage where you want to learn Breakpoint in Pycharm

Even if your code has no bug, go to the Run/Debug menu:

Debug in Pycharm

Execution will stop at the breakpoint and you'll now be able to see all the variables and step through your code line by line.

Watch and step in Pycharm

Look at all the variables after each single line. Compare the values to what you think the values should be. If there is a mismatch, it's likely a misunderstanding on your side, not by Python. Do that a few times and it'll be obvious why and how the string is reversed.

  • Related