Sample Problem on Mock Test

Can someone explain this block of code? I do not understand why the answer is 6.
Thank you!

i = 1
x = 3
sum = 0
while (i <= x):
    sum += i
    i += 1
print(sum)

It’s the sum of the number from 1 to 3: 1 + 2 + 3 = 6

Hey, @andrewmejia
you can also rewrite this block of code using for loop, to make it a little bit easy to read and understand

sum = 0
for i in range(1,4):
  sum += i

range is a special function that returns integer iterator, it’s frequently used to make a sequence of numbers fast

So, in a for loop, on each iteration i would increase by 1 starting from 1 and ends on 3. Be definition range doesn’t include last number

1st instance, i value=1 sum = sum + i // 0+1 =1
2nd instance, i value=2 sum = sum + i // 1+2 = 3
3rd instance, i value =3 sum = sum + i // 3+3 =6

Hi,

In the first iteration, i is 1, so sum becomes 1.
In the second iteration, i is 2, so sum becomes 3 (1 + 2).
In the third iteration, i is 3, so sum becomes 6 (3 + 3).

Thanks

Plus-Equel operator can be confusing. “sum += i” is same as “sum = sum+1” and “i += 1” is same as “i=i+1” …

To write the effect of such operators algebraically,

a += b is shorthand for a = a + b whatever the values are so,

  • sum += i is sum = sum + i
  • i += 1 is i = i + 1

Follows exactly the same for all these operators… -=, *=, /=, %=