string - Reverse exercise (Python Codecademy course, part "Practice makes perfect" 15/15) -


the task runs follows: define function called reverse takes string textand returns string in reverse.you may not use reversed or [::-1] this.

my code works right want understand 1 detail. tks all.

def reverse (text):     result = ''     in range (len(text)-1,-1,-1):         result += text[i]     return result 

the point wrote in 3rd line for in range (len(text)-1,0,-1):but program returned '!nohty' instead of '!nohtyp'. changed (len(text)-1,-1,-1) ant it's ok. why?!

because text (python!) of 7 length , lists 0 based (starting 0) , loop decreasing, need have -1.

the string "python!" 7 characters. range exclusive final number, range accounting 6, 5, 4, 3, 2, 1, 0.

the length - 1 = 6, range of 6 -1, -1 exclusive accounts numbers 0 - 6. because lists 0 based, accounts all. 0 range's second argument, numbers 6, 5, 4, 3, 2, 1, doesn't account whole word.

for example:

the word "stack" has 5 letters. once list, occupies indices 0, 1, 2, 3, 4. looping through whole word, need access 0th element. that, range must go -1 exclusive.

for loop:

>>> range(6, -1, -1) [6, 5, 4, 3, 2, 1, 0] 

then, when access doing:

text = "python!" in range(len(text)-1, -1, -1):     print(text[i]) 

text[i] accesses individual characters , prints them, backwards.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -