🐍 第02课:基础语法

—— 万丈高楼平地起

🏆 变量/类型/运算/字符串全通过
✅ Python验证通过

📌 本课目标

1️⃣ 变量与数据类型

Python 是动态类型语言,变量不需要声明类型,但每个值都有明确的类型。

# 基本数据类型
name = "张三"           # str 字符串
age = 28                 # int 整数
height = 1.75             # float 浮点数
is_student = True          # bool 布尔值
hobbies = ["编程", "阅读"]  # list 列表
info = {"city": "北京"}     # dict 字典
unique = {1, 2, 3}          # set 集合
point = (3, 4)             # tuple 元组
nothing = None             # NoneType 空值

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

类型提示(Type Hints)

# Python 3.12+ 推荐使用类型提示
def greet(name: str, age: int) -> str:
    return f"你好,{name}!你{age}岁了。"

# 使用 Python 3.12 新语法(更简洁的类型联合)
def process(value: str | int) -> str:
    return str(value).upper()

2️⃣ 运算符大全

算术运算符

# 基本运算
print(10 + 3)    # 13  加法
print(10 - 3)    # 7   减法
print(10 * 3)    # 30  乘法
print(10 / 3)    # 3.333...  除法(总是返回float)
print(10 // 3)   # 3   整除
print(10 % 3)    # 1   取模
print(10 ** 3)   # 1000 幂运算

# divmod 同时获取商和余数
quotient, remainder = divmod(10, 3)
print(f"商={quotient}, 余={remainder}")  # 商=3, 余=1

比较运算符

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

# 链式比较(Python独有特色)
x = 5
print(1 < x < 10)   # True
print(1 < x > 3)    # True

逻辑运算符

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

# 短路求值
result = 0 or "默认值"      # "默认值"
result = "有值" or "默认值"  # "有值"
name = None
display = name or "匿名"     # "匿名"

位运算符

print(0b1010 & 0b1100)    # 8   (0b1000) 按位与
print(0b1010 | 0b1100)    # 14  (0b1110) 按位或
print(0b1010 ^ 0b1100)    # 6   (0b0110) 按位异或
print(~0b1010)             # -11         按位取反
print(1 << 4)              # 16          左移
print(16 >> 2)             # 4           右移

3️⃣ 字符串操作

创建与基本操作

s1 = '单引号'
s2 = "双引号"
s3 = """三引号
可以
换行"""

# 常用操作
s = "Hello, Python!"
print(len(s))           # 14
print(s.upper())        # HELLO, PYTHON!
print(s.lower())        # hello, python!
print(s.strip())        # 去除首尾空白
print(s.split(", "))    # ['Hello', 'Python!']
print(s.replace("Python", "World"))  # Hello, World!
print(s.startswith("Hello"))   # True
print(s.endswith("!"))        # True
print(s.count("o"))          # 2
print(s.find("Python"))     # 7

字符串格式化(三种方式)

name = "张三"
age = 28
score = 95.678

# 1. f-string(推荐!Python 3.6+)
print(f"姓名: {name}, 年龄: {age}")
print(f"分数: {score:.2f}")      # 保留2位: 95.68
print(f"{'居中':=^20}")          # ========居中========

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

# 3. % 格式化(旧式,不推荐)
print("姓名: %s, 年龄: %d" % (name, age))

f-string 高级用法

# 表达式
print(f"2的10次方 = {2**10}")        # 1024
print(f"列表长度 = {len([1,2,3])}")   # 3

# 调用函数
print(f"现在: {__import__('datetime').datetime.now():%Y-%m-%d}")

# 对齐与填充
print(f"{'左对齐':<20}")     # 左对齐                  
print(f"{'右对齐':>20}")     #                   右对齐
print(f"{'居中':^20}")      #          居中          
print(f"{42:08d}")          # 00000042
print(f"{3.14159:.4f}")     # 3.1416
print(f"{0.85:.1%}")        # 85.0%
print(f"{255:#x}")          # 0xff
print(f"{1024:,}")          # 1,024 千分位

4️⃣ 类型转换

# 显式转换
print(int("42"))         # 42
print(float("3.14"))      # 3.14
print(str(42))            # "42"
print(bool(0))            # False
print(bool(1))            # True
print(list("abc"))        # ['a', 'b', 'c']
print(tuple([1,2,3]))    # (1, 2, 3)

# 假值(falsy values)
falsy = [0, 0.0, "", None, False, [], {}, set()]
for v in falsy:
    print(f"{v!r:>10} -> {bool(v)}")

# 安全转换
def safe_int(value, default=0):
    try:
        return int(value)
    except (ValueError, TypeError):
        return default

print(safe_int("123"))     # 123
print(safe_int("abc"))     # 0
print(safe_int("abc", -1))  # -1

5️⃣ 验证脚本

#!/usr/bin/env python3
"""第02课 基础语法验证"""

def test_variables_and_types():
    """变量与类型测试"""
    name = "张三"
    age = 28
    height = 1.75
    is_dev = True

    assert type(name) == str
    assert type(age) == int
    assert type(height) == float
    assert type(is_dev) == bool
    print("✅ 变量与类型测试通过")

def test_operators():
    """运算符测试"""
    assert 10 + 3 == 13
    assert 10 - 3 == 7
    assert 10 * 3 == 30
    assert 10 / 3 == 10 / 3  # 浮点数
    assert 10 // 3 == 3
    assert 10 % 3 == 1
    assert 2 ** 10 == 1024
    assert divmod(10, 3) == (3, 1)
    # 链式比较
    assert 1 < 5 < 10
    print("✅ 运算符测试通过")

def test_string_operations():
    """字符串操作测试"""
    s = "Hello, Python!"
    assert len(s) == 14
    assert s.upper() == "HELLO, PYTHON!"
    assert s.lower() == "hello, python!"
    assert s.split(", ") == ["Hello", "Python!"]
    assert s.replace("Python", "World") == "Hello, World!"
    assert s.startswith("Hello")
    assert s.endswith("!")
    assert s.count("o") == 2

    # f-string
    name, score = "张三", 95.678
    assert f"{name}" == "张三"
    assert f"{score:.2f}" == "95.68"
    assert f"{1024:,}" == "1,024"
    print("✅ 字符串操作测试通过")

def test_type_conversion():
    """类型转换测试"""
    assert int("42") == 42
    assert float("3.14") == 3.14
    assert str(42) == "42"
    assert bool(0) == False
    assert bool(1) == True
    assert list("abc") == ["a", "b", "c"]

    # 安全转换
    def safe_int(v, d=0):
        try:
            return int(v)
        except (ValueError, TypeError):
            return d
    assert safe_int("123") == 123
    assert safe_int("abc") == 0
    print("✅ 类型转换测试通过")

def test_falsy_values():
    """假值测试"""
    falsy = [0, 0.0, "", None, False, [], {}, set()]
    for v in falsy:
        assert not v, f"{v!r} 应该为假"
    print("✅ 假值测试通过")

if __name__ == "__main__":
    test_variables_and_types()
    test_operators()
    test_string_operations()
    test_type_conversion()
    test_falsy_values()
    print("\n🎉 第02课全部验证通过!")
✅ 变量与类型测试通过 ✅ 运算符测试通过 ✅ 字符串操作测试通过 ✅ 类型转换测试通过 ✅ 假值测试通过 🎉 第02课全部验证通过!

🔑 本课要点

  1. 动态类型——变量类型由值决定,但每个值都有明确类型
  2. f-string——最优雅的字符串格式化方式,Python 3.6+
  3. 链式比较——1 < x < 101 < x and x < 10 更 Pythonic
  4. 短路求值——value or default 是最简单的默认值模式
  5. 类型提示——不强制,但让代码更易读、更易维护