Python 与 C 对照
同一个程序分别用 Python 和 C 编写,取自本课程的课时。
打印与注释
Python 会为你格式化对象。C 的 printf 使用格式字符串,其中的转换说明符必须与参数类型匹配;%d 会打印 int。注释使用 // 或 /* ... */。换行符需要在 C 格式字符串中显式写出。
Python1print("value=7")C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10printf("value=%d\n",7);11return 0;12}布尔值与分支
Python 的真值判定也会考虑容器是否为空。在 C 中,标量零为假,非零标量为真;非空指针为真,即使它指向空字符串也是如此。需要明确的布尔结果时,可以使用 stdbool.h 中的 bool。
Python1print(bool(""))C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10const char *s=""; printf("%s\n",s?"true":"false");11return 0;12}数组需要长度
Python 列表会记录自己的长度。C 数组的元素数量固定,但函数的数组参数会调整为指针,因此不会记录元素数量。单独传入 size_t 长度,并确保遵守它;C 不会检查下标。
Python1a=[2,4,6]2print(len(a))C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10int a[]={2,4,6};printf("%zu\n",sizeof a/sizeof a[0]);11return 0;12}函数参数是值
Python 参数绑定到对象的引用。C 参数接收的是值的副本。更改 int 参数无法更改调用方的变量。指针参数也会被复制,但它可以指向调用方拥有的存储空间,函数可能会修改该空间。
Python1def change(n):2 n=93x=24change(x)5print(x)C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8static void change(int n){n=9;(void)n;}9int main(void) {10int x=2;change(x);printf("%d\n",x);11return 0;12}地址与解引用
Python 提供引用,但不提供通用地址运算。在 C 中,&object 获取地址,*pointer 访问指针指向的对象。只能解引用指向有效且仍然存活的正确类型对象的指针。空指针和悬空指针不是普通的空值。
Python1box=[2]2alias=box3alias[0]=54print(box[0])C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10int n=2;int *p=&n;*p=5;printf("%d\n",n);11return 0;12}解析并返回状态结果
Python 的 int 要么返回一个值,要么引发 ValueError。C 库解析器使用显式的状态信息。sscanf 会报告成功赋值的次数,但仅仅匹配前缀并不能证明整个输入都有效。单独进行一次验证可以确保输入符合严格的语法。
Python1text="12x"2print(text.isascii() and text.isdigit())C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10const char *s="12x";int ok=*s!=0;for(size_t i=0;s[i];i++)if(s[i]<'0'||s[i]>'9')ok=0;printf("%d\n",ok);11return 0;12}
课程大纲
10 章48 节课1 个项目48 个挑战99 道测验题常见问题
面向 Python 开发者的 C 适合谁学习?
适合已经会写 Python、想学 C 的人。每节课都从你熟悉的 Python 代码出发,展示 C 如何实现同样的事情,所以你可以跳过入门基础。
需要先会 C 吗?
不需要。课程从你的第一个 C 程序开始。你需要掌握 Python 基础:变量、条件、循环、函数和集合。
面向 Python 开发者的 C 有多少节课?
面向 Python 开发者的 C 包含 48 节互动课,你可以按自己的节奏完成。
面向 Python 开发者的 C 包含哪些内容?
本课程分为以下几章:编译与计算, 条件与循环, 数组与文本, 函数与接口, and more。
面向 Python 开发者的 C 免费吗?
是的。Coddy 上的每门课程都可以免费开始。你可以直接在浏览器中完成课程,无需下载,也无需注册。