BeginnerCoder

Lesson 2 — Reverse a string

Build the answer one piece at a time

A string is a sequence of characters, and a for loop visits them left to right. To reverse a word, start with an empty result and put each new character in front of what you already have. After "c", "a", "t" the result grows "c" → "ac" → "tac".

result = ""
result = "c" + result   # "c"
result = "a" + result   # "ac"

(Python also has the shortcut s[::-1], but here you build it yourself.)

Why it matters: "start empty, add one piece per step" is called accumulating, and it is one of the most common patterns in programming.

Want it another way?
Task

Inside the loop, put ch in front of result. Expected: olleh, then nohtyp.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.