Skip to main content
 首页 » 编程设计

python之变量初始化之Python

2025年01月19日14kuangbin

我不明白这个问题

为什么 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 没有任何贡献。

希望对你有帮助