Bill
Bill

Reputation: 27

Variable initialization - Python

I don't understand this problem

Why counter can be equal to 1 i=1 (like in the code below) or can be replaced by i = 0 and the result is the same?

n = 4
sum = 0  # initialize sum
i = 1  # initialize counter
while i <= n:
    sum = sum + i
    i = i+1  # update counter
print("The sum is", sum)

Upvotes: 2

Views: 947

Answers (1)

Vasif
Vasif

Reputation: 1413

# with added line numbers

1. while i < n: # modified this for simplicity.
2.     sum = sum + i
3.     i = i+1    # update counter
4. print("The sum is", sum)

Here is the execution to wrap your head around it.

# L1: i=1 n=4 sum=0
# L2: i=1 n=4 sum=1
# L3: i=2 n=4 sum=1
# L1: check i<n - True, 2 is less than 4
# L2: i=2 n=4 sum=3
# L3: i=3 n=4 sum=3
# L1: check i<n - True, 3 is less than 4
# L2: i=3 n=4 sum=6
# L3: i=4 n=4 sum=6
# L1: check i<n - False, 4 not less than 4 ; its equal. condition fail.
# L4: print 6

In case of starting from 0.

# L1: i=0 n=4 sum=0
# L2: i=0 n=4 sum=0 # see sum is 0+0
# L3: i=1 n=4 sum=0

# L1: check i<n - True, 1 is less than 4
# L2: i=1 n=4 sum=1
# L3: i=2 n=4 sum=1
# L1: check i<n - True, 2 is less than 4
# L2: i=2 n=4 sum=3
# L3: i=3 n=4 sum=3
# L1: check i<n - True, 3 is less than 4
# L2: i=3 n=4 sum=6
# L3: i=4 n=4 sum=6
# L1: check i<n - False, 4 not less than 4 ; its equal. condition fail.
# L4: print 6

When you contrast both; you did an extra iteration of work in the second case. But, that contributes nothing to the sum.

Hope this helps

Upvotes: 1

Related Questions