Skip to content

Commit e49ddc7

Browse files
authored
Added solution for Episode 12 For Loops - Reversing a String
1 parent 48253e3 commit e49ddc7

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

episodes/12-for-loops.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,35 @@ print(total)
237237
> print(result)
238238
> ~~~
239239
> {: .python}
240+
> >
241+
> > ## Solution
242+
> >
243+
> > `result` is an empty string because we use it to build or accumulate on our reverse string. `char` is the loop variable for `original`. Each time through the loop `char` takes on one value from `original`. Use `char` with `result` to control the order of the string. Our loop code should look like this:
244+
> > ~~~
245+
> > original = "tin"
246+
> > result = ""
247+
> > for char in original:
248+
> > result = char + result
249+
> > print(result)
250+
> > nit
251+
> > ~~~
252+
> > If you were to expand out the loop the iterations would look something like this:
253+
> > ~~~
254+
> > #First loop
255+
> > char = "t"
256+
> > result = ""
257+
> > char + result = "t"
258+
> > #Second loop
259+
> > char = 'i"
260+
> > result = "t"
261+
> > char + result = "it"
262+
> > #Third loop
263+
> > char = "n"
264+
> > result = "it"
265+
> > char + result = "nit"
266+
> > ~~~
267+
> > {: .python}
268+
> {: .solution}
240269
{: .challenge}
241270
242271
> ## Practice Accumulating

0 commit comments

Comments
 (0)