Python学习——Python 与 C 语法对比4(循环)

承接上篇:

Python学习——Python 与 C 语法对比1(输出、注释、运算符、数字型)-CSDN博客

Python学习——Python 与 C 语法对比2(非数字型)-CSDN博客

Python学习——Python 与 C 语法对比3(条件控制)-CSDN博客

循环

语法PythonC
for循环for i in range(start, end, step):
# do something
for (int i = start; i < end; i += step) {
// do something
}
while循环while condition:
# do something
while (condition) {
// do something
}
do-while循环Python没有内置的do-while循环,但可以使用while循环结合break语句实现do {
// do something
} while (condition);

举例:for

python:

for i in range(6):
    print(i)

c:

#include <stdio.h>

int main() {
    for (int i = 0; i < 6; i++) {
        printf("%d\n", i);
    }
    return 0;
}

这段代码会输出从 0 到 5 的整数。

举例:while 

python:

count = 0
while count < 6:
    print(count)
    count += 1

c:

#include <stdio.h>

int main() {
    int count = 0;
    while (count < 6) {
        printf("%d\n", count);
        count++;
    }
    return 0;
}

这段代码会输出从 0 到 5 的整数。

举例:do-while 

python:

count = 0
while True:
    print("Python loop iteration:", count)
    count += 1
    if count >= 3:
        break

c:

#include <stdio.h>

int main() {
    int count = 0;
    do {
        printf("C loop iteration: %d\n", count);
        count++;
    } while (count < 3);
    return 0;
}

这段代码会输出从 0 到 2 的整数,然后退出循环。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值