变量初始化 - Python

时间:2017-12-13 07:10:34

标签: python variables while-loop initialization

我不明白这个问题

为什么counter可以等于1 i=1(如下面的代码中所示)或者可以用i = 0代替,结果是一样的?

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)

1 个答案:

答案 0 :(得分:1)

# 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)

这是围绕它的执行。

# 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

从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

当你对比两者时;你在第二种情况下做了额外的迭代工作。但是,这对sum没有任何贡献。

希望这有帮助