Can anyone explain this code?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#


No error

I just have questions

def reverse(x):
    string = ""
    length= len(x) - 1
    while length >=0:
        string += x[length]
        length = length -1 
    return string
    
print reverse('Geo')


#2

How did this code reverse the text , im sorry
im new to coding
i just want to understand it , i dont want to just copy and paste codes that i dont understand


#3

copy paste coding and then getting it explained is the same like math homework, you need to make the task, completing the exercises to push to the next level, no explanation is going to fix that

your while loop loops from right to left and appending to string, which will the string to reverse


#4

def reverse(x):
1. You defined a function reverse that takes string x..

Inside the function

string = ""
1. you defined a local empty string.

length= len(x) - 1
2. You saved the 1 less from length of string inside length variable.

while length >=0:
3. You defined a while loop that will loop until the length of string is greater or equal to 0.

Inside the while loop

string += x[length]
1. For each iteration , Youre adding last letter of string as first letter inside the empty string variable string

length = length -1
2. You're reducing value of length at each iteration.

return string
3. When while loop condition does not satisfies
It gets out of loop and the last line of code inside the function return string returns the final reversed string

Lets put Geo as input.

  1. string variable is an empty string.
  2. You put length of Geo which is 3 minus 1 in length variable.
    now length variable carry value 2.
  3. Loop starts, it checks if length is greater or equal to 0
    yes...
    it adds last element of string Geo as
    Geo[2] returns o and its get added to empty string variable string.
  4. We reduce one from length variable

  5. Loop keeps going until length >= 0.

  6. At last we return reverse of string which is oeG

Its how the whole thing works.

but as @stetim94 said , AVOID COPY PASTING!
Hope it helps! :slight_smile:


#5

Thank you for the explanation
I didn't copy paste at all
I just wanted it to be explained


#6

Great then! :slight_smile: Kudos to you!
Keep up the good work! :thumbsup:


#7

Thanks a lot ! :smiley:
I will do my best!


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.