📜  C 和Pythonfor 循环的区别

📅  最后修改于: 2021-09-13 02:59:20             🧑  作者: Mango

For 循环通常用于顺序遍历。它属于确定迭代的范畴。确定迭代意味着预先明确指定重复次数。但是,c 和Python for 循环的工作方式有所不同,尽管两者都用于迭代,但工作方式不同。

C 中的 For 循环

C 中的 for 循环从初始化值开始,然后检查条件。如果测试表达式为真,则执行 for 下的代码,并且没有任何异常,更新表达式方程相应地增加或减少变量。

句法:

程序

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)


输出:

Python的For 循环

Python的for 循环适用于给定的范围。与其声明一起给出的变量名称是从初始值开始更改其值,然后相应地递增或递减。循环适用于比结束值少 1 的值。

句法

在哪里,

x=初始值

y=最终值

z=增加/减少

程序

蟒蛇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)

输出

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