如何在python中执行循环时减少和增加循环范围'i'变量

时间:2015-06-04 10:14:57

标签: python

我是python中的新手,我不知道为什么当我在执行for循环时递增它时,这个程序没有更新'i'变量。 len(a) = 10 你可以在代码中看到我正在逐渐增加'i'时间,但是当我进入循环迭代时它增加后,它会使循环体中的更新无效。这是为什么?它应该一般更新,循环执行应该小于10.请帮助。

final_result = 0
a= '3 4  4 5 6'
for i in range(0,len(a)):
    print('iteration')
    print('i is = ')      
    print(i)
    if a[i] is ' ' and a[i+1] is not ' ':
        if i-1 is 0:
            final_result = int(a[i-1]) + int(a[i+1])
            i += 2                           //here goes the increment
            print('1a- m here')
            print(final_result)
            print('i is = ')
            print(i)
        else:
            final_result = final_result + int(a[i+1])
            i += 2                              //here goes the increment
            print('1b- m here')
            print(final_result)
    elif a[i] is ' ' and a[i+1] is ' ':
        if i-1 is 0: 
            final_result = int(a[i-1]) - int(a[i+1])
            i += 3                           //here goes the increment
            print('2a- m here')
            print(final_result)
        else:
            final_result = final_result - int(a[i+2])
            i += 3                                 //here goes the increment
            print('2b- m here')
            print(final_result)
            print('i is = ')
            print(i)
print(final_result)

1 个答案:

答案 0 :(得分:1)

所以有几件事:

  • 使用while循环。
  • 初始化i = 0
  • 当您的条件不匹配时增加i += 1
  • Python中的注释使用# comment编写,而不是// comment

示例:

final_result = 0
a = '3 4  4 5 6'
i = 0
while i < len(a):
    print('iteration')
    print('i is = ')
    print(i)
    if a[i] is ' ' and a[i + 1] is not ' ':
        if i - 1 is 0:
            final_result = int(a[i - 1]) + int(a[i + 1])
            i += 2  # here goes the increment
            print('1a- m here')
            print(final_result)
            print('i is = ')
            print(i)
        else:
            final_result = final_result + int(a[i + 1])
            i += 2  # here goes the increment
            print('1b- m here')
            print(final_result)
    elif a[i] is ' ' and a[i + 1] is ' ':
        if i - 1 is 0:
            final_result = int(a[i - 1]) - int(a[i + 1])
            i += 3  # here goes the increment
            print('2a- m here')
            print(final_result)
        else:
            final_result = final_result - int(a[i + 2])
            i += 3  # here goes the increment
            print('2b- m here')
            print(final_result)
            print('i is = ')
            print(i)
    else:
        i += 1
print(final_result)

<强>输出:

$ python3.4 foo.py
iteration
i is = 
0
iteration
i is = 
1
1a- m here
7
i is = 
3
iteration
i is = 
3
2b- m here
3
i is = 
6
iteration
i is = 
6
1b- m here
8
iteration
i is = 
8
1b- m here
14
14