On this page

Python 语法

Python 语法详解

Python 以其简洁明了的语法而闻名,下面我将详细介绍 Python 的主要语法元素。

1. 基础语法规则

缩进

Python 使用缩进来表示代码块(通常为4个空格):

if 5 > 2:
    print("5大于2")  # 缩进表示属于if语句的代码块

注释

# 这是单行注释

"""
这是多行注释
可以跨越多行
"""

语句分隔

一般每行一条语句,也可用分号分隔:

x = 5; y = 10; print(x + y)

2. 变量与数据类型

变量命名

my_var = 10           # 合法
_variable = "hello"   # 合法
2var = 5              # 非法(不能以数字开头)

基本数据类型

# 数字
x = 10       # 整数(int)
y = 3.14     # 浮点数(float)
z = 2 + 3j   # 复数(complex)

# 字符串
s1 = '单引号'
s2 = "双引号"
s3 = """多行
字符串"""

# 布尔值
t = True
f = False

3. 运算符

算术运算符

print(10 + 3)   # 13
print(10 - 3)   # 7
print(10 * 3)   # 30
print(10 / 3)   # 3.333...
print(10 // 3)  # 3 (整除)
print(10 % 3)   # 1 (取模)
print(10 ** 3)  # 1000 (幂运算)

比较运算符

print(10 > 3)   # True
print(10 == 3)  # False
print(10 != 3)  # True

逻辑运算符

print(True and False)  # False
print(True or False)   # True
print(not True)        # False

4. 数据结构

列表(List)

my_list = [1, 2, 3, "a", "b"]
my_list.append("c")    # 添加元素
print(my_list[0])      # 1 (索引从0开始)

元组(Tuple)

my_tuple = (1, 2, 3)   # 不可变序列
print(my_tuple[1])     # 2

字典(Dict)

my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"])  # Alice
my_dict["age"] = 26     # 修改值

集合(Set)

my_set = {1, 2, 3}
my_set.add(4)          # 添加元素
print(2 in my_set)     # True

5. 控制流

if-elif-else

x = 10
if x > 10:
    print("大于10")
elif x == 10:
    print("等于10")
else:
    print("小于10")

for循环

for i in range(5):     # 0到4
    print(i)

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

while循环

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

6. 函数

定义函数

def greet(name="World"):
    """这是一个问候函数"""
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!
print(greet())         # Hello, World!

Lambda函数

square = lambda x: x ** 2
print(square(5))  # 25

7. 异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零")
else:
    print("结果:", result)
finally:
    print("执行完毕")

8. 文件操作

# 写入文件
with open("example.txt", "w") as f:
    f.write("Hello, Python!")

# 读取文件
with open("example.txt", "r") as f:
    content = f.read()
    print(content)

9. 面向对象编程

类与对象

class Dog:
    # 类属性
    species = "Canis familiaris"
    
    # 初始化方法
    def __init__(self, name, age):
        self.name = name  # 实例属性
        self.age = age
    
    # 实例方法
    def description(self):
        return f"{self.name} is {self.age} years old"
    
    # 另一个实例方法
    def speak(self, sound):
        return f"{self.name} says {sound}"

# 创建实例
my_dog = Dog("Buddy", 5)
print(my_dog.description())
print(my_dog.speak("Woof Woof"))

10. 模块与导入

# 导入整个模块
import math
print(math.pi)

# 导入特定函数
from datetime import datetime
print(datetime.now())

# 使用别名
import numpy as np

Python 的语法设计强调可读性和简洁性,这使得它成为初学者和专业开发人员的理想选择。掌握这些基础语法后,你可以进一步学习 Python 的高级特性和各种应用领域的库。