承接上篇:
Python学习——Python 与 C 语法对比1(输出、注释、运算符、数字型)-优快云博客
Python学习——Python 与 C 语法对比2(非数字型)-优快云博客
Python学习——Python 与 C 语法对比3(条件控制)-优快云博客
循环
| 语法 | Python | C |
|---|---|---|
| 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 的整数,然后退出循环。
1381

被折叠的 条评论
为什么被折叠?



