我不明白这个问题

为什么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)

最佳答案

# 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没有任何贡献。

希望这可以帮助

关于python - 变量初始化-Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47787405/

10-13 03:52