Home โบ Problems โบ String multiplication in a loop
String multiplication in a loop
๐ง Predict the output Topic: strings Difficulty: medium Free
What this problem practises
Python strings are immutable sequences. "Fixing" a string always produces a new one, so the return value has to be captured; slicing rules apply, and every method โ upper(), strip(), split(), join() โ behaves differently from the in-place mutation you might be picturing.
This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.
Difficulty: medium โ expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.
The challenge
The code runs in PyDebugโs in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.
The snippet
The interactive editor pre-fills exactly this code โ read it, then submit your prediction:
for i in range(1, 4):
print("*" * i)Understand the rule
This snippet combines two rules that are individually simple: s * n repeats a string, and a loop accumulator grows on every pass. Together they produce patterns like staircases ('*', '**', '***') โ or, when the multiplication uses the loop variable, output whose size changes each iteration. The reliable technique is a value table: one row per iteration.
How to trace it
- Create a table with columns for the loop variable and every accumulator.
- Fill one row per iteration, computing the repetition count from that iteration's loop value.
- Note whether the print is inside the loop (one line per row) or after it (only the final row).
- Check the loop's range boundaries โ the first and last rows are where predictions usually break.
Common wrong fixes
- Multiplying by the number of iterations instead of the loop variable's current value (they differ when range starts at 0).
- Forgetting that '*' * 0 is an empty string, which prints as a blank line, not nothing.
- Losing track of whether the accumulator resets inside the loop or persists across passes.
Rule to remember
For loops that build strings, trace with a value table โ iteration by iteration. The output is the table's print column, and boundary rows catch most wrong answers.
๐ฎ Learning path: Output Prediction
Problem 3 of 18 in this path. Work them in order โ each one builds on the rule before it.
โ String multiplication and indexingNext in path: String case methods โ
More strings problems
Keep going
- Output-prediction strategies โ how to predict tricky snippets without running them.
- Browse every strings problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.