Step-by-Step Explanation
-
Initialize a variable:
-
A variable total is created and set to 0. It will be used to accumulate the sum.
-
-
For loop:
range(1, 5) generates the numbers: 1, 2, 3, 4 (remember, the end is exclusive).
-
The loop adds each of these values to total.
Here's what happens on each iteration:
i = 1: total = 0 + 1 = 1
i = 2: total = 1 + 2 = 3
i = 3: total = 3 + 3 = 6
i = 4: total = 6 + 4 = 10
-
Print the result:
-
It prints the final value of total, which is:
-
✅ Output:
Key Concept:
range(start, end) includes the start but excludes the end.
+= is a shorthand for total = total + i.


0 Comments:
Post a Comment