Will
Will

Reputation: 47

I do not understand why this function reverses the string

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.

Upvotes: 0

Views: 70

Answers (3)

Thomas Weller
Thomas Weller

Reputation: 59410

It looks to me as if you are in a stage where you want to learn how to debug small programs.

For questions on StackOverflow, you want to provide a minimal reproducible example. What does that mean in your case?

  1. "repoducible" means that you should not depend on user input. Replace user input by hardcoded values.
  2. "minimal" means that you don't call the function twice. Once is enough.

For that reason, I'll not walk you through your original program, but through this one instead:

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

print(reverse("abcdef"))

I'll use a free program called PyCharm Community Edition. You set a breakpoint where you want to understand how things work. Since you don't understand the reverse() method, put it right at the beginning of that method. You do that by clicking between the line number and the text:

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.

Upvotes: 4

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

Upvotes: 1

Mahmoud Nasser
Mahmoud Nasser

Reputation: 850

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.

Upvotes: 1

Related Questions