承接上篇:
Python学习——Python 与 C 语法对比1(输出、注释、运算符、数字型)-CSDN博客
Python学习——Python 与 C 语法对比2(非数字型)-CSDN博客
Python学习——Python 与 C 语法对比3(条件控制)-CSDN博客
Python学习——Python 与 C 语法对比4(循环)-CSDN博客
Python学习——Python 与 C 语法对比5(函数)-CSDN博客
输入输出
语法 | Python | C |
---|---|---|
输入 | input("请输入你的名字:") | char name[50]; scanf("%s", name); |
输出 | print("你好," ) | printf("你好,\n"); |
区别点:
- Python使用缩进来表示代码块,而C使用大括号
{}
。 - Python的变量不需要声明类型,而C需要指定变量的类型。
- Python的函数定义使用
def
关键字,而C使用返回值类型作为函数签名的一部分。 - Python的输入输出使用
input()
和print()
函数,而C使用scanf()
和printf()
函数。
举例:函数定义、默认参数
Python:
name = input("请输入你的名字:")
print("你好," + name + "!")
C:
#include <stdio.h>
int main() {
char name[50];
printf("请输入你的名字:");
scanf("%s", name);
printf("你好,%s!\n", name);
return 0;
}
格式化输出
语法 | Python | C |
---|---|---|
格式化字符串 | "Hello, {}!".format("world") | `printf("Hello, %s!\n", "world");` |
格式化整数 | "The number is {:d}.".format(42) | `printf("The number is %d.\n", 42);` |
格式化浮点数 | "The float value is {:.2f}.".format(3.14159) | `printf("The float value is %.2f.\n", 3.14159);` |
格式化宽度 | "{:10}".format("hello") | `printf("%10s\n", "hello");` |
格式化对齐 | "{:<10}".format("hello") | `printf("%-10s\n", "hello");` |
区别点:
- Python使用
str.format()
方法进行字符串格式化,而C使用printf()
函数。 - Python的格式化字符串使用大括号
{}
作为占位符,而C使用%s
、%d
等格式说明符。 - Python支持更多的格式化选项,如指定小数点后的位数(
:.2f
)、指定宽度(:10
)和对齐方式(:<10
表示左对齐)。 - C语言的
printf()
函数需要手动计算并传递参数的数量和类型,而Python的str.format()
方法会自动处理这些细节。
举例:函数定义、默认参数
Python:
name = "Alice"
age = 30
print("My name is {:10} and I am {:d} years old.".format(name, age))
C:
#include <stdio.h>
int main() {
char *name = "Alice";
int age = 30;
printf("My name is %-10s and I am %d years old.\n", name, age);
return 0;
}