Q.Write the output of the following Python code: for i in range(2,7,2): print(i * '$')
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The range(2, 7, 2) function generates the numbers 2, 4, and 6. For each of these numbers, the code prints the $ character repeated that many times, resulting in three lines of output: $$, $$$$, and $$$$$$.
The core of this problem lies in understanding two fundamental Python concepts: how the range() function generates sequences of numbers and how string multiplication works.
The range() function is commonly used to produce a sequence of integers, which is particularly useful for controlling for loops. When used as range(start, stop, step), it generates numbers starting from start, incrementing by step each time, and continues up to, but not including, the stop value. The stop value is always exclusive.
String multiplication in Python is straightforward: when you multiply a string by an integer (e.g., string * integer), the string is repeated integer times. For instance, 'abc' * 2 results in 'abcabc'.
Let's trace the execution step by step.
-
Analyze
range(2, 7, 2):- The
startvalue is 2. - The
stopvalue is 7 (exclusive). - The
stepvalue is 2. - The sequence of numbers generated by
range(2, 7, 2)will be:- Start at 2.
- Add the step (2): $2 + 2 = 4$.
- Add the step (2): $4 + 2 = 6$.
- Add the step (2): $6 + 2 = 8$. Since 8 is not less than the
stopvalue of 7, this number is not included in the sequence.
- Therefore, the
forloop will iterate withitaking the values 2, 4, and 6.
- The
-
First Iteration:
i = 2:- The code inside the loop is
print(i * '$'). - Substituting
iwith 2, we getprint(2 * '$'). - String multiplication
2 * '$'repeats the$character two times, resulting in the string'$$'. * Theprint()function outputs this string, followed by a newline character. * Output so far: ``` $$
- The code inside the loop is
-
Second Iteration:
i = 4:- The code is
print(i * '$'). …
- The code is
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.