我是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)
答案 0 :(得分:1)
所以有几件事:
while
循环。i = 0
i += 1
# 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