Problem with 5, reverse exercise


#1

Hi,

So the goal of the exercise was to make a function that reverses the string put into it, and correct code for this exercise is

def reverse(text):
word = “”
l = len(text) - 1
while l >= 0:
word = word + text[l]
l -= 1
return word

Now I understand that the function reverse takes a string text as input, but I dont understand why the variable word was defined with empty brackets, (an empty string?) and what went on from below there… Thanks in advance!


#2

Empty quotes.
You are building a new word that is the reverse of another word. It makes sense to start from scratch. The rest of the code adds the last letter of the given word to your blank string one letter at a time


#3

Alright, thanks! I understand it better now, but still dont get why we would subtract one from the variable l at the end, Im confused by l being defined as a string and then subtracting 1 from that string first and then again at the end…


#4

How the reverse code works


#5

l is not defined as a string. It’s a number. It’s originally defined as the length of the string minus one.

Human-readable:

Define a function called reverse, that takes an argument called text. In that function:
Create a variable called word, that is nothing but an empty string
Create a variable called l, that is one shorter than the number of letters in text.
Use that number until it’s zero, to do the following over and over:
Look up the letter in text that’s at that number’s position, and put it in word.
Decrease our counter, which will put us back one position when we do this again to get the next letter
When there are no positions left because we’ve already done position 0, spit out the string we’ve built.


#6

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