Veloris.
返回索引
概念基础 2026-02-14

Python基本语法:没有大括号没有分号,靠缩进写代码是什么体验?

5 分钟
1.6k words

Python基本语法:没有大括号没有分号,靠缩进写代码是什么体验?

Python以”优雅”和”简洁”著称,其语法设计与C语言有很大不同。本篇将介绍Python的基本语法规则、代码风格规范(PEP 8),并与C语言进行对比,帮助你快速适应Python的编程方式。


1. 代码结构:缩进与代码块

1.1 缩进规则

Python使用缩进来表示代码块,而不是C语言的大括号{}

基本规则

  • 同一代码块的语句必须有相同的缩进
  • 推荐使用4个空格作为一级缩进(PEP 8标准)
  • 不要混用Tab和空格
# 正确的缩进
if True:
    print("条件为真")      # 4个空格缩进
    if True:
        print("嵌套条件")  # 8个空格缩进
    print("回到外层")      # 4个空格缩进
print("最外层")            # 无缩进

1.2 与C语言的对比

C语言

if (condition) {
    printf("条件为真\n");
    if (another_condition) {
        printf("嵌套条件\n");
    }
    printf("回到外层\n");
}
printf("最外层\n");

Python

if condition:
    print("条件为真")
    if another_condition:
        print("嵌套条件")
    print("回到外层")
print("最外层")
对比项C语言Python
代码块标识{} 大括号缩进
条件后无需冒号需要冒号:
条件括号必须()可选(通常不写)
语句结束分号;换行

1.3 缩进错误示例

# ❌ 错误:缩进不一致
if True:
    print("第一行")
   print("第二行")  # IndentationError: unexpected indent

# ❌ 错误:缺少缩进
if True:
print("没有缩进")  # IndentationError: expected an indented block

# ❌ 错误:混用Tab和空格
if True:
    print("空格缩进")
	print("Tab缩进")  # TabError: inconsistent use of tabs and spaces

💡 建议:在VS Code中设置”将Tab转换为空格”,避免混用问题。


2. 注释

2.1 单行注释

使用#开头,#后面的内容都是注释。

# 这是一个单行注释
print("Hello")  # 这是行尾注释

# 计算两数之和
a = 10
b = 20
result = a + b  # 将a和b相加

与C语言对比

语言单行注释多行注释
C// 注释/* 注释 */
Python# 注释"""注释"""'''注释'''

2.2 多行注释

Python没有专门的多行注释语法,通常使用多个#或三引号字符串:

# 方法1:多个单行注释
# 这是第一行注释
# 这是第二行注释
# 这是第三行注释

# 方法2:三引号字符串(不推荐用于普通注释)
"""
这是多行注释
可以写很多行
但实际上这是一个字符串
"""

2.3 文档字符串(Docstring)

文档字符串是Python特有的,用于为模块、函数、类添加说明文档。

def calculate_area(length, width):
    """
    计算矩形面积。
    
    Args:
        length: 矩形的长度
        width: 矩形的宽度
    
    Returns:
        矩形的面积
    
    Example:
        >>> calculate_area(3, 4)
        12
    """
    return length * width

# 查看文档
print(calculate_area.__doc__)
help(calculate_area)

💡 提示:VS Code安装autoDocstring插件后,输入"""会自动生成文档模板。


3. 变量与赋值

3.1 变量定义

Python是动态类型语言,变量无需声明类型,直接赋值即可。

# Python:直接赋值,类型自动推断
name = "张三"        # 字符串
age = 25             # 整数
height = 1.75        # 浮点数
is_student = True    # 布尔值

# 查看变量类型
print(type(name))    # <class 'str'>
print(type(age))     # <class 'int'>

与C语言对比

// C语言:必须声明类型
char name[] = "张三";
int age = 25;
float height = 1.75;
int is_student = 1;  // C没有布尔类型(C99之前)
特性C语言Python
类型声明必须不需要
类型检查编译时运行时
类型转换显式/隐式显式为主
变量可变类型不可以可以
# Python变量可以改变类型(但不推荐)
x = 10       # x是整数
x = "hello"  # x变成字符串(合法但不推荐)

3.2 多重赋值

Python支持多种便捷的赋值方式:

# 同时给多个变量赋相同的值
a = b = c = 0
print(a, b, c)  # 0 0 0

# 同时给多个变量赋不同的值(解包赋值)
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# 交换两个变量的值(Python特色!)
a, b = 10, 20
a, b = b, a      # 一行搞定交换
print(a, b)      # 20 10

# C语言交换需要临时变量
# int temp = a; a = b; b = temp;

3.3 变量命名规则

合法的变量名

  • 由字母、数字、下划线组成
  • 不能以数字开头
  • 不能是Python关键字
  • 区分大小写
# ✅ 合法的变量名
name = "张三"
_private = 100
user_name = "admin"
userName = "admin"  # 合法但不推荐(Python习惯用下划线)
MAX_SIZE = 1000     # 常量用全大写

# ❌ 非法的变量名
# 2name = "错误"    # 不能以数字开头
# user-name = "错误" # 不能包含连字符
# class = "错误"    # 不能是关键字

4. 语句与表达式

4.1 语句结束

Python使用换行表示语句结束,不需要分号。

# Python:换行即结束
print("Hello")
print("World")

# 也可以用分号(但不推荐)
print("Hello"); print("World")

4.2 多行语句

当一条语句太长时,可以使用以下方式换行:

# 方法1:反斜杠续行
total = 1 + 2 + 3 + \
        4 + 5 + 6 + \
        7 + 8 + 9

# 方法2:括号内自动续行(推荐)
total = (1 + 2 + 3 +
         4 + 5 + 6 +
         7 + 8 + 9)

# 方法3:列表、字典、函数参数自动续行
my_list = [
    "apple",
    "banana",
    "cherry",
]

result = some_function(
    arg1,
    arg2,
    arg3,
)

4.3 同一行多条语句

虽然可以用分号分隔,但不推荐

# 不推荐
a = 1; b = 2; c = 3

# 推荐
a = 1
b = 2
c = 3

5. 输入与输出

5.1 print函数

# 基本输出
print("Hello, World!")

# 输出多个值(默认用空格分隔)
print("姓名:", "张三", "年龄:", 25)
# 输出:姓名: 张三 年龄: 25

# 自定义分隔符
print("2024", "12", "18", sep="-")
# 输出:2024-12-18

# 自定义结尾(默认是换行\n)
print("Hello", end=" ")
print("World")
# 输出:Hello World

# 输出到文件
with open("output.txt", "w") as f:
    print("写入文件", file=f)

与C语言printf对比

功能C语言Python
基本输出printf("Hello\n");print("Hello")
格式化printf("%d", num);print(f"{num}")
换行需要\n自动换行
多值输出需要多个格式符直接逗号分隔

5.2 input函数

# 获取用户输入(返回字符串)
name = input("请输入姓名:")
print(f"你好,{name}!")

# 输入数字需要类型转换
age = int(input("请输入年龄:"))
height = float(input("请输入身高:"))

# 一行输入多个值
x, y = input("输入两个数(空格分隔):").split()
x, y = int(x), int(y)

# 更简洁的写法
x, y = map(int, input("输入两个数:").split())

与C语言scanf对比

// C语言
char name[50];
int age;
printf("请输入姓名:");
scanf("%s", name);
printf("请输入年龄:");
scanf("%d", &age);
# Python
name = input("请输入姓名:")
age = int(input("请输入年龄:"))

5.3 格式化输出

Python有三种字符串格式化方式:

方式1:f-string(推荐,Python 3.6+)

name = "张三"
age = 25
score = 95.5

# 基本用法
print(f"姓名:{name},年龄:{age}")

# 表达式
print(f"明年{age + 1}岁")

# 格式控制
print(f"分数:{score:.2f}")      # 保留2位小数:95.50
print(f"分数:{score:>10.2f}")   # 右对齐,宽度10:     95.50
print(f"十六进制:{255:#x}")      # 0xff
print(f"二进制:{10:#b}")         # 0b1010

方式2:format方法

print("姓名:{},年龄:{}".format(name, age))
print("姓名:{0},年龄:{1}".format(name, age))
print("姓名:{n},年龄:{a}".format(n=name, a=age))

方式3:%格式化(老式,类似C语言)

print("姓名:%s,年龄:%d" % (name, age))
print("分数:%.2f" % score)

格式化速查表

格式说明示例
{:d}整数f"{10:d}"10
{:f}浮点数f"{3.14:f}"3.140000
{:.2f}保留2位小数f"{3.14159:.2f}"3.14
{:s}字符串f"{'hello':s}"hello
{:>10}右对齐,宽度10f"{'hi':>10}" hi
{:<10}左对齐,宽度10f"{'hi':<10}"hi
{:^10}居中,宽度10f"{'hi':^10}" hi
{:,}千位分隔符f"{1000000:,}"1,000,000
{:%}百分比f"{0.25:%}"25.000000%
{:#x}十六进制f"{255:#x}"0xff
{:#b}二进制f"{10:#b}"0b1010

6. 关键字与标识符

6.1 Python关键字

Python有35个关键字(Python 3.10+),不能用作变量名:

import keyword
print(keyword.kwlist)
类别关键字
布尔/空值True, False, None
逻辑运算and, or, not
条件判断if, elif, else
循环for, while, break, continue
函数/类def, return, class, lambda
异常处理try, except, finally, raise
导入import, from, as
上下文with
其他pass, yield, global, nonlocal, assert, del, in, is, async, await

6.2 标识符规则

# ✅ 推荐的命名风格
user_name = "admin"      # 变量:小写+下划线
MAX_CONNECTIONS = 100    # 常量:全大写+下划线
def calculate_sum():     # 函数:小写+下划线
    pass
class UserAccount:       # 类:大驼峰
    pass

# ⚠️ 特殊命名约定
_private = "私有变量"     # 单下划线开头:约定为私有
__mangled = "名称修饰"    # 双下划线开头:名称修饰
__init__ = "魔术方法"     # 双下划线包围:特殊方法

7. PEP 8代码风格规范

7.1 什么是PEP 8

PEP 8是Python官方的代码风格指南,全称”Python Enhancement Proposal 8”。遵循PEP 8可以让代码更易读、更统一。

官方文档:https://peps.python.org/pep-0008/

7.2 核心规范

缩进

# ✅ 使用4个空格
def function():
    if True:
        print("正确")

# ❌ 使用Tab或其他空格数
def function():
	if True:  # Tab缩进
	  print("错误")  # 2空格缩进

行长度

# ✅ 每行不超过79个字符(代码)或72个字符(注释/文档)
result = some_function(
    argument1, argument2, argument3
)

# ❌ 过长的行
result = some_function(argument1, argument2, argument3, argument4, argument5)

空行

# 顶层函数和类之间:2个空行
def function1():
    pass


def function2():
    pass


class MyClass:
    # 类内方法之间:1个空行
    def method1(self):
        pass

    def method2(self):
        pass

空格

# ✅ 正确的空格使用
x = 1
y = x + 1
my_list = [1, 2, 3]
my_dict = {"key": "value"}
func(arg1, arg2)

# ❌ 错误的空格使用
x=1                    # 赋值符号两边无空格
y = x+1                # 运算符两边空格不一致
my_list = [1,2,3]      # 逗号后无空格
my_dict = {"key":"value"}
func( arg1, arg2 )     # 括号内多余空格

导入

# ✅ 正确的导入顺序和格式
# 1. 标准库
import os
import sys

# 2. 第三方库
import pandas as pd
import numpy as np

# 3. 本地模块
from mymodule import myfunction

# ❌ 错误的导入
import os, sys  # 不要在一行导入多个模块
from os import *  # 避免使用通配符导入

7.3 命名约定

类型命名风格示例
变量小写+下划线user_name, total_count
常量全大写+下划线MAX_SIZE, PI
函数小写+下划线calculate_sum(), get_user()
大驼峰UserAccount, HttpRequest
模块小写+下划线my_module.py
私有单下划线开头_private_var
强私有双下划线开头__very_private

与C语言命名习惯对比

类型C语言习惯Python习惯
变量userNameuser_nameuser_name
常量MAX_SIZEMAX_SIZE
函数calculateSumcalculate_sumcalculate_sum
结构体/类UserAccountUserAccount

8. Python vs C语言:语法对比总结

语法元素C语言Python
代码块{ }缩进
语句结束;换行
注释///* */#
变量声明int x = 10;x = 10
条件语句if (x > 0) { }if x > 0:
循环for (i=0; i<10; i++)for i in range(10):
函数定义int func(int a) { }def func(a):
布尔值0/1true/falseTrue/False
空值NULLNone
逻辑运算&&, ||, !and, or, not
字符串char[]char*str
数组int arr[10]list
输出printf()print()
输入scanf()input()

代码对比示例

// C语言:判断奇偶数
#include <stdio.h>

int main() {
    int num;
    printf("请输入一个整数:");
    scanf("%d", &num);
    
    if (num % 2 == 0) {
        printf("%d是偶数\n", num);
    } else {
        printf("%d是奇数\n", num);
    }
    
    return 0;
}
# Python:判断奇偶数
num = int(input("请输入一个整数:"))

if num % 2 == 0:
    print(f"{num}是偶数")
else:
    print(f"{num}是奇数")

9. 常见错误与避坑

❌ 错误1:缩进错误

# 错误:缩进不一致
if True:
    print("第一行")
   print("第二行")  # IndentationError

# 正确
if True:
    print("第一行")
    print("第二行")

❌ 错误2:忘记冒号

# 错误:if后面没有冒号
if True
    print("Hello")  # SyntaxError

# 正确
if True:
    print("Hello")

❌ 错误3:用==判断None

# 不推荐
if x == None:
    pass

# 推荐:用is判断
if x is None:
    pass

❌ 错误4:混淆=和==

# 错误:在条件中使用=
if x = 10:  # SyntaxError(Python不允许)
    pass

# 正确
if x == 10:
    pass

# Python 3.8+的海象运算符(特殊情况)
if (n := len(data)) > 10:
    print(f"数据量:{n}")

❌ 错误5:中文标点

# 错误:使用中文标点
print"Hello"# SyntaxError
name = "张三"  # 中文引号

# 正确:使用英文标点
print("Hello")
name = "张三"

10. 实战练习

练习1:个人信息卡片

"""
练习:创建个人信息卡片
要求:
1. 使用input获取姓名、年龄、职业
2. 使用f-string格式化输出
3. 遵循PEP 8规范
"""

# 获取用户输入
name = input("请输入姓名:")
age = int(input("请输入年龄:"))
occupation = input("请输入职业:")

# 格式化输出
print("\n" + "=" * 30)
print(f"{'个人信息卡片':^26}")
print("=" * 30)
print(f"姓名:{name}")
print(f"年龄:{age}岁")
print(f"职业:{occupation}")
print("=" * 30)

练习2:温度转换器

"""
练习:摄氏度与华氏度转换
公式:F = C × 9/5 + 32
"""

celsius = float(input("请输入摄氏温度:"))
fahrenheit = celsius * 9 / 5 + 32

print(f"{celsius:.1f}°C = {fahrenheit:.1f}°F")

练习3:简单计算器

"""
练习:简单计算器
要求:输入两个数和运算符,输出结果
"""

num1 = float(input("请输入第一个数:"))
operator = input("请输入运算符(+、-、*、/):")
num2 = float(input("请输入第二个数:"))

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "错误:除数不能为0"
else:
    result = "错误:无效的运算符"

print(f"结果:{num1} {operator} {num2} = {result}")

11. 总结

🔑 核心要点

知识点要点
缩进4个空格,不混用Tab
注释#单行,"""文档字符串
变量无需声明类型,动态类型
语句结束换行,不需要分号
格式化输出推荐f-string
命名规范变量/函数用小写下划线,类用大驼峰

✅ 学习检查清单

  • 理解Python的缩进规则
  • 掌握三种注释方式
  • 能正确使用print和input
  • 掌握f-string格式化输出
  • 了解PEP 8基本规范
  • 能对比Python和C语言的语法差异

📖 下一步学习

掌握了基本语法后,让我们深入学习Python的数据类型:


常见问题 FAQ

💬 Python的缩进用空格还是Tab?

PEP 8规定用4个空格。绝对不要混用空格和Tab,否则会报IndentationError。VS Code中设置Tab Size为4并勾选”Insert Spaces”即可。

💬 f-string、format()、%格式化用哪个?

优先用f-string(Python 3.6+),可读性最好。format()适合需要复用模板的场景。%格式化是老写法,新代码不建议用。

💬 Python变量不用声明类型,怎么知道类型对不对?

type()查看类型,用类型提示(type hints)标注:def add(a: int, b: int) -> int:。配合Pylance可以在编辑时就发现类型错误。


参考资料


系列导航

End of file.