For 循环通常用于顺序遍历。它属于确定迭代的范畴。确定迭代意味着预先明确指定重复次数。但是,c 和Python for 循环的工作方式有所不同,尽管两者都用于迭代,但工作方式不同。
C 中的 For 循环
C 中的 for 循环从初始化值开始,然后检查条件。如果测试表达式为真,则执行 for 下的代码,并且没有任何异常,更新表达式方程相应地增加或减少变量。
句法:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example 1:
for(int i=1;i<=10;i++)
{
printf(“%d “,i);
}
OUTPUT
1 2 3 4 5 6 7 8 9 10
It stops executing the body of for loop whenever i becomes greater than 10.
Example 2:
for(int i=1;i<=10;i++)
{
i=i+1
printf(“%d “,i);
}
OUTPUT:
2 4 6 10
//because each time i is getting incremented by 1 in for body and whenever i>10 it stops the execution.
程序
C
//Program to show working of for loop in C
#include
int main()
{
// code
for (int i = 1; i <= 10; i++)
{
// it will have effect on termination
// condition
i=i+1;
printf("%d\n", i);
}
return 0;
}
Python3
# program to show for loop in python
for i in range(1, 11):
# it will have no effect in termination
# condition
i = i+1
# it will always iterate for 10 times as
# given in range
print(i)
输出:
2
4
6
8
10
Python的For 循环
Python的for 循环适用于给定的范围。与其声明一起给出的变量名称是从初始值开始更改其值,然后相应地递增或递减。循环适用于比结束值少 1 的值。
句法
for val in range(x,y,z)
在哪里,
x=初始值
y=最终值
z=增加/减少
Example 1:
for i in range(1,11):
print(i)
OUTPUT:
1 2 3 4 5 6 7 8 9 10
//as we can see it is iterating for 10 times ie(11-1)=10 times
Example 2:
for i in range(1,11):
i=1+1;
print(i)
OUTPUT:
2 3 4 5 6 7 8 9 10 11
//though we are incrementing i inside the for body still it is iterating for 10 times.
程序
蟒蛇3
# program to show for loop in python
for i in range(1, 11):
# it will have no effect in termination
# condition
i = i+1
# it will always iterate for 10 times as
# given in range
print(i)
输出
2
3
4
5
6
7
8
9
10
11
c 和Python for 循环的区别
C | Python |
---|---|
The for loop in C executes a statement or a block of statements repeatedly until a specified expression evaluates to false | The foreach loop in Python repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum. |
Evaluation of expression decides execution | No such evaluation required |
Increment or decrement operation has to be specified explicitly | If not given it is assumed to be +1 |