for循环中python变量的范围 [英] Scope of python variable in for loop
问题描述
这是我遇到问题的 Python 代码:
for i in range (0,10):如果我==5:我+=3打印我
我希望输出是:
<预><代码>0123489然而,解释器吐了:
<预><代码>0123486789我知道 for
循环在 C 中为变量创建了一个新的作用域,但对 Python 一无所知.为什么i
的值在Python的for
循环中没有变化,有什么补救方法可以得到预期的输出?
for循环遍历range(10)
中的所有数字,即[0,1,2,3,4,5,6,7,8,9]
.
您更改 i
的 当前 值不会影响范围内的下一个值.
您可以通过 while 循环获得所需的行为.
i = 0当我 <10:# 随心所欲地做事和操作 `i`如果我==5:我+=3打印我# 不要忘记手动增加`i`我 += 1
Here's the Python code I'm having problems with:
for i in range (0,10):
if i==5:
i+=3
print i
I expected the output to be:
0
1
2
3
4
8
9
However, the interpreter spits out:
0
1
2
3
4
8
6
7
8
9
I know that a for
loop creates a new scope for a variable in C, but have no idea about Python. Why does the value of i
not change in the for
loop in Python, and what's the remedy to it to get the expected output?
The for loop iterates over all the numbers in range(10)
, that is, [0,1,2,3,4,5,6,7,8,9]
.
That you change the current value of i
has no effect on the next value in the range.
You can get the desired behavior with a while loop.
i = 0
while i < 10:
# do stuff and manipulate `i` as much as you like
if i==5:
i+=3
print i
# don't forget to increment `i` manually
i += 1
这篇关于for循环中python变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!