Java循环和Python循环的区别

一句话总结:JAVA循环中的变量i是动态分配的,可以被改变的。而Python循环中的i是在初始化时就被分配在了内存中,无法改变。实验:

JAVA for循环:

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
int count = 0;
for (int i=0; i<6; i++){
i++;
System.out.println(i);
count++;
}
System.out.println(count);
}

输出结果:
1
3
5
count : 3
也就是只循环了3次,因为我们在循环中改变了i的值。

Python for循环:

1
2
3
4
5
6
count = 0
for i in range(6):
i += 1
print(i)
count += 1
print("count:" + str(count))

输出结果:
1
2
3
4
5
6
count:6
可见,在循环内部修改的i在下次循环时还会变回默认的值,因为range(6)相当于直接分配了一个[0~5]的数组,i会在这个数组中遍历取值。