Skip to content

基础语法

Python 是一种简洁、易读、功能强大的编程语言,广泛应用于 Web 开发、数据分析、人工智能等领域。

第一个 Python 程序

python
# hello.py
print("Hello, World!")

# 运行: python hello.py

变量与数据类型

变量

python
# 变量声明(无需指定类型)
name = "张三"
age = 25
height = 1.75
is_student = True

# 多变量赋值
a, b, c = 1, 2, 3
x = y = z = 0

# 交换变量
a, b = b, a

# 查看类型
print(type(name))   # <class 'str'>
print(type(age))    # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>

数字类型

python
# 整数
a = 100
b = -50
c = 0xFF    # 十六进制
d = 0o77    # 八进制
e = 0b1010  # 二进制

# 浮点数
pi = 3.14159
scientific = 1.5e-10  # 科学计数法

# 复数
z = 3 + 4j
print(z.real)   # 3.0
print(z.imag)   # 4.0

# 数字运算
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 幂运算

# 数学函数
abs(-5)         # 5 绝对值
round(3.14159, 2)  # 3.14 四舍五入
max(1, 2, 3)    # 3 最大值
min(1, 2, 3)    # 1 最小值
pow(2, 10)      # 1024 幂运算

import math
math.floor(3.7)   # 3 向下取整
math.ceil(3.2)    # 4 向上取整
math.sqrt(16)     # 4.0 平方根
math.sin(math.pi / 2)  # 1.0 正弦

字符串

python
# 字符串定义
s1 = 'Hello'
s2 = "World"
s3 = '''多行
字符串'''
s4 = """多行
字符串"""

# 转义字符
print("Hello\nWorld")  # 换行
print("Hello\tWorld")  # 制表符
print("Hello\\World")  # 反斜杠

# 原始字符串
raw_str = r"C:\Users\name"
print(raw_str)  # C:\Users\name

# 字符串操作
s = "Hello, World!"
print(len(s))           # 13 长度
print(s[0])             # H 索引
print(s[-1])            # ! 负索引
print(s[0:5])           # Hello 切片
print(s[7:])            # World!
print(s[:5])            # Hello
print(s[::2])           # Hlo ol 步长
print(s[::-1])          # !dlroW ,olleH 反转

# 字符串方法
s = "  Hello, World!  "
print(s.strip())        # "Hello, World!" 去空格
print(s.lower())        # "  hello, world!  "
print(s.upper())        # "  HELLO, WORLD!  "
print(s.replace("World", "Python"))
print(s.split(","))     # ['  Hello', ' World!  ']
print(",".join(["a", "b", "c"]))  # "a,b,c"
print(s.startswith("  H"))  # True
print(s.endswith("!  "))     # True
print(s.find("World"))       # 9
print(s.count("l"))          # 3

# 格式化字符串
name = "张三"
age = 25

# f-string (Python 3.6+)
print(f"姓名: {name}, 年龄: {age}")
print(f"明年: {age + 1}岁")

# format 方法
print("姓名: {}, 年龄: {}".format(name, age))
print("姓名: {0}, 年龄: {1}".format(name, age))
print("姓名: {name}, 年龄: {age}".format(name=name, age=age))

# % 格式化
print("姓名: %s, 年龄: %d" % (name, age))
print("浮点数: %.2f" % 3.14159)

# 字符串判断
s = "Hello123"
print(s.isalpha())    # False 是否全是字母
print(s.isdigit())    # False 是否全是数字
print(s.isalnum())    # True 是否全是字母或数字
print(s.isupper())    # False 是否全大写
print(s.islower())    # False 是否全小写

布尔值

python
# 布尔值
is_true = True
is_false = False

# 比较运算
print(5 > 3)   # True
print(5 < 3)   # False
print(5 == 5)  # True
print(5 != 3)  # True
print(5 >= 5)  # True
print(5 <= 3)  # False

# 逻辑运算
print(True and False)  # False 与
print(True or False)   # True 或
print(not True)        # False 非

# 短路求值
a = 0
result = a != 0 and 10 / a > 1  # 不会报错

# 假值
# False, None, 0, 0.0, '', [], (), {}, set()

类型转换

python
# 转整数
int(3.14)       # 3
int("123")      # 123
int("0xFF", 16) # 255

# 转浮点数
float(3)        # 3.0
float("3.14")   # 3.14

# 转字符串
str(123)        # "123"
str(3.14)       # "3.14"
str(True)       # "True"

# 转布尔值
bool(1)         # True
bool(0)         # False
bool("")        # False
bool("hello")   # True

# 转列表
list("hello")   # ['h', 'e', 'l', 'l', 'o']
list((1, 2, 3)) # [1, 2, 3]

# 转元组
tuple([1, 2, 3])  # (1, 2, 3)

# 转集合
set([1, 2, 2, 3])  # {1, 2, 3}

运算符

算术运算符

python
a, b = 10, 3

print(a + b)   # 13 加
print(a - b)   # 7  减
print(a * b)   # 30 乘
print(a / b)   # 3.333... 除
print(a // b)  # 3  整除
print(a % b)   # 1  取余
print(a ** b)  # 1000 幂运算

# 自增(Python 没有 ++)
a += 1  # a = a + 1
a -= 1  # a = a - 1
a *= 2  # a = a * 2
a /= 2  # a = a / 2

比较运算符

python
a, b = 5, 10

print(a == b)  # False
print(a != b)  # True
print(a > b)   # False
print(a < b)   # True
print(a >= b)  # False
print(a <= b)  # True

# 链式比较
x = 5
print(1 < x < 10)  # True
print(1 < x and x < 10)  # 等价

逻辑运算符

python
a, b = True, False

print(a and b)  # False 与
print(a or b)   # True 或
print(not a)    # False 非

# 短路求值
def check():
    print("检查")
    return True

False and check()   # 不会调用 check()
True or check()     # 不会调用 check()

成员运算符

python
lst = [1, 2, 3, 4, 5]

print(3 in lst)      # True
print(6 in lst)      # False
print(6 not in lst)  # True

s = "Hello World"
print("World" in s)  # True

d = {"name": "张三", "age": 25}
print("name" in d)   # True(检查键)

身份运算符

python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is c)      # True 同一对象
print(a is b)      # False 不同对象
print(a is not b)  # True
print(a == b)      # True 值相等

# 小整数缓存
x = 256
y = 256
print(x is y)  # True

x = 257
y = 257
print(x is y)  # False(可能)

位运算符

python
a = 5   # 0101
b = 3   # 0011

print(a & b)   # 1  (0001) 按位与
print(a | b)   # 7  (0111) 按位或
print(a ^ b)   # 6  (0110) 按位异或
print(~a)      # -6 按位取反
print(a << 1)  # 10 (1010) 左移
print(a >> 1)  # 2  (0010) 右移

控制流程

条件语句

python
# if 语句
age = 18

if age >= 18:
    print("成年")
elif age >= 12:
    print("青少年")
else:
    print("儿童")

# 单行 if
status = "成年" if age >= 18 else "未成年"

# 多条件
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

# 检查多个条件
x = 5
if x > 0 and x < 10:
    print("0 < x < 10")

if 0 < x < 10:  # 更 Pythonic
    print("0 < x < 10")

# 检查是否为空
lst = []
if not lst:
    print("列表为空")

# 检查 None
value = None
if value is None:
    print("值为 None")

循环语句

for 循环

python
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "Hello":
    print(char)

# 使用 range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# 带索引遍历
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# 同时遍历多个列表
names = ["张三", "李四", "王五"]
ages = [25, 30, 28]
for name, age in zip(names, ages):
    print(f"{name}: {age}岁")

# 遍历字典
person = {"name": "张三", "age": 25, "city": "北京"}

for key in person:
    print(key)

for key, value in person.items():
    print(f"{key}: {value}")

for value in person.values():
    print(value)

while 循环

python
# 基本循环
count = 0
while count < 5:
    print(count)
    count += 1

# 带条件
while True:
    response = input("继续吗?(y/n): ")
    if response.lower() == 'n':
        break

# while-else
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("循环结束")

break、continue 和 pass

python
# break - 跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)  # 0, 1, 2, 3, 4

# continue - 跳过当前迭代
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 1, 3, 5, 7, 9

# pass - 占位符
for i in range(5):
    pass  # 什么都不做

def todo():
    pass  # 待实现

循环中的 else

python
# for-else
for i in range(5):
    if i == 10:
        break
else:
    print("循环正常结束")  # 会执行

# 查找示例
numbers = [1, 2, 3, 4, 5]
target = 3
for num in numbers:
    if num == target:
        print(f"找到: {target}")
        break
else:
    print("未找到")

列表推导式

基本语法

python
# 基本形式
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# 带条件
evens = [x for x in numbers if x % 2 == 0]
print(evens)  # [2, 4]

# 带条件表达式
result = ["偶数" if x % 2 == 0 else "奇数" for x in numbers]
print(result)  # ['奇数', '偶数', '奇数', '偶数', '奇数']

# 嵌套循环
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 多变量
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)  # [(0,0), (0,1), (0,2), (1,0), ...]

字典推导式

python
# 基本形式
numbers = [1, 2, 3, 4, 5]
squares_dict = {x: x ** 2 for x in numbers}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 交换键值
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped)  # {1: 'a', 2: 'b', 3: 'c'}

# 带条件
scores = {"张三": 85, "李四": 92, "王五": 78}
passed = {name: score for name, score in scores.items() if score >= 80}
print(passed)  # {'张三': 85, '李四': 92}

集合推导式

python
# 基本形式
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {x ** 2 for x in numbers}
print(unique_squares)  # {1, 4, 9, 16}

生成器表达式

python
# 使用圆括号
numbers = [1, 2, 3, 4, 5]
squares_gen = (x ** 2 for x in numbers)
print(squares_gen)  # <generator object>

# 惰性求值
for square in squares_gen:
    print(square)

# 转换为列表
squares_list = list(x ** 2 for x in numbers)

# 内存效率
# 列表推导式:立即生成所有元素
# 生成器表达式:按需生成

函数

函数定义

python
# 基本函数
def greet():
    print("Hello!")

greet()

# 带参数
def greet(name):
    print(f"Hello, {name}!")

greet("张三")

# 带返回值
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # 8

# 多返回值
def get_info():
    return "张三", 25, "北京"

name, age, city = get_info()

# 返回字典
def get_person():
    return {"name": "张三", "age": 25}

person = get_person()

参数类型

python
# 位置参数
def greet(name, age):
    print(f"{name}, {age}岁")

greet("张三", 25)

# 关键字参数
greet(name="张三", age=25)
greet(age=25, name="张三")

# 默认参数
def greet(name, age=18):
    print(f"{name}, {age}岁")

greet("张三")      # 张三, 18岁
greet("李四", 25)  # 李四, 25岁

# 可变位置参数
def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3, 4, 5))  # 15

# 可变关键字参数
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="张三", age=25, city="北京")

# 混合参数
def func(a, b, *args, **kwargs):
    print(f"a={a}, b={b}")
    print(f"args={args}")
    print(f"kwargs={kwargs}")

func(1, 2, 3, 4, name="张三", age=25)
# a=1, b=2
# args=(3, 4)
# kwargs={'name': '张三', 'age': 25}

# 仅位置参数 (Python 3.8+)
def greet(name, /, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("张三")           # 正确
greet("张三", "Hi")     # 正确
# greet(name="张三")    # 错误

# 仅关键字参数
def greet(*, name, age):
    print(f"{name}, {age}岁")

greet(name="张三", age=25)  # 正确
# greet("张三", 25)         # 错误

文档字符串

python
def calculate_bmi(weight, height):
    """
    计算身体质量指数 (BMI)

    Args:
        weight: 体重(千克)
        height: 身高(米)

    Returns:
        float: BMI 值

    Raises:
        ValueError: 如果身高或体重为负数

    Example:
        >>> calculate_bmi(70, 1.75)
        22.857...
    """
    if weight <= 0 or height <= 0:
        raise ValueError("体重和身高必须为正数")
    return weight / (height ** 2)

# 访问文档字符串
print(calculate_bmi.__doc__)
help(calculate_bmi)

Lambda 函数

python
# 基本语法
square = lambda x: x ** 2
print(square(5))  # 25

# 多参数
add = lambda a, b: a + b
print(add(5, 3))  # 8

# 条件表达式
is_even = lambda x: "偶数" if x % 2 == 0 else "奇数"
print(is_even(4))  # 偶数

# 在排序中使用
students = [("张三", 85), ("李四", 92), ("王五", 78)]
students.sort(key=lambda x: x[1], reverse=True)
print(students)  # [('李四', 92), ('张三', 85), ('王五', 78)]

# 在 filter 中使用
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# 在 map 中使用
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

高阶函数

python
# map - 映射
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 多序列
a = [1, 2, 3]
b = [4, 5, 6]
sums = list(map(lambda x, y: x + y, a, b))
print(sums)  # [5, 7, 9]

# filter - 过滤
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# reduce - 归约
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 15

# sorted - 排序
students = [{"name": "张三", "age": 25}, {"name": "李四", "age": 22}]
sorted_students = sorted(students, key=lambda x: x["age"])
print(sorted_students)

闭包

python
# 闭包示例
def outer(x):
    def inner(y):
        return x + y
    return inner

add5 = outer(5)
print(add5(3))  # 8

# 计数器
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

c = counter()
print(c())  # 1
print(c())  # 2
print(c())  # 3

装饰器基础

python
# 简单装饰器
def my_decorator(func):
    def wrapper():
        print("函数执行前")
        func()
        print("函数执行后")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# 函数执行前
# Hello!
# 函数执行后

# 带参数的装饰器
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("函数执行前")
        result = func(*args, **kwargs)
        print("函数执行后")
        return result
    return wrapper

@my_decorator
def add(a, b):
    return a + b

result = add(5, 3)

实践示例

学生成绩管理

python
def main():
    students = []

    while True:
        print("\n===== 学生成绩管理系统 =====")
        print("1. 添加学生")
        print("2. 显示所有学生")
        print("3. 查找学生")
        print("4. 统计信息")
        print("5. 退出")

        choice = input("请选择: ")

        if choice == "1":
            name = input("姓名: ")
            scores = []
            for subject in ["语文", "数学", "英语"]:
                score = float(input(f"{subject}成绩: "))
                scores.append(score)

            student = {
                "name": name,
                "scores": scores,
                "total": sum(scores),
                "average": sum(scores) / len(scores)
            }
            students.append(student)
            print("添加成功!")

        elif choice == "2":
            if not students:
                print("暂无学生数据")
                continue

            print("\n姓名\t语文\t数学\t英语\t总分\t平均")
            print("-" * 50)
            for s in sorted(students, key=lambda x: x["total"], reverse=True):
                print(f"{s['name']}\t{s['scores'][0]}\t{s['scores'][1]}\t"
                      f"{s['scores'][2]}\t{s['total']}\t{s['average']:.1f}")

        elif choice == "3":
            name = input("请输入姓名: ")
            found = [s for s in students if s["name"] == name]
            if found:
                s = found[0]
                print(f"\n姓名: {s['name']}")
                print(f"语文: {s['scores'][0]}")
                print(f"数学: {s['scores'][1]}")
                print(f"英语: {s['scores'][2]}")
                print(f"总分: {s['total']}")
                print(f"平均: {s['average']:.1f}")
            else:
                print("未找到该学生")

        elif choice == "4":
            if not students:
                print("暂无学生数据")
                continue

            all_scores = [s["total"] for s in students]
            print(f"\n学生人数: {len(students)}")
            print(f"最高总分: {max(all_scores)}")
            print(f"最低总分: {min(all_scores)}")
            print(f"平均总分: {sum(all_scores) / len(all_scores):.1f}")

        elif choice == "5":
            print("再见!")
            break

if __name__ == "__main__":
    main()