for循环中的python变量的作用域 [英] Scope of python variable in for loop

查看:165
本文介绍了for循环中的python变量的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 对于范围(0,10)中的我:
如果我== 5:
我+ = 3
打印我

输出为:

  0 
1
2
3
4
8
9

然而解释器吐出:

  0 
1
2
3
4
8
6
7
8
9

我知道一个 for 循环为C中的一个变量创建一个新的作用域,但对python不知道。任何人都可以解释为什么 i 的值在python中循环的不会改变,以及它是如何得到的预期的输出。

解决方案

for循环遍历范围内的所有数字(10) code>,也就是 [0,1,2,3,4,5,6,7,8,9]

您更改 i current 值对范围中的下一个值没有影响。



您可以通过while循环获得所需的行为。

  i = 0 
while i< ; 10:
#做的东西,操纵`i`就像你喜欢
,如果我== 5:
我+ = 3

打印我

#不要忘记手动增加`i`
i + = 1


Heres the python code im 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. Can anyone explain why the value of i doesnt change in the for loop in python and whats 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆