第一讲 Python语言基础

完整的学习资料已经添加到绑定资源里,有需要的小伙伴可以下载,给博主点个关注吧,你们的支持是我创作最大的动力~

一、核心知识点

1. Python特点
  • 面向对象:一切皆对象
  • 可读性好:强制缩进,语法简洁
  • 开源免费:自由软件
  • 解释型语言:无需编译,直接运行源代码
  • 动态类型:变量类型在运行时确定
2. 基本数据类型
类型 说明 示例
int 整型 10, -5
float 浮点型 3.14, 2.5e10
complex 复数 3+4j, 3+4J
str 字符串 'hello', "world"
bool 布尔型 True, False
NoneType 空类型 None

重要:Python没有char类型,单个字符也是字符串。

3. 常用内置函数
函数 功能 示例
type() 查看变量类型 type(3.14)<class 'float'>
id() 查看内存地址 id(x)
len() 返回长度 len("abc")3
eval() 执行字符串表达式 eval("2+4/5")2.8
input() 用户输入(返回字符串) x = input("提示:")
print() 输出 print("Hello")
4. 运算符优先级(由高到低)
  1. ** 幂运算
  2. +x, -x, ~x 正负号、按位取反
  3. *, /, //, % 乘除、整除、取模
  4. +, - 加减
  5. <<, >> 位移
  6. & 按位与
  7. ^ 按位异或
  8. | 按位或
  9. 比较运算符
  10. not, and, or 逻辑运算

关键运算符

  • //:整商(地板除)
  • %:取模(余数)
  • **:幂运算(2**31-1 计算 231−12^{31}-12311
5. 复数表示

Python中使用 jJ 表示虚部:

c = 3 + 4j  # 实部3,虚部4
6. 标识符规则
  • 由字母、数字、下划线组成
  • 不能以数字开头
  • 不能是关键字(如break, for等)
  • 区分大小写
  • 合法示例_7a_b, _
  • 非法示例3Q, i'm, a$b, break
7. 字符串转义与原始字符串
s = 'a\nb\tc'  # \n换行,\t制表符,len(s) = 5(a,\n,b,\t,c)
print(r"\nGood")  # 原始字符串,输出:\nGood
8. 变量与内存

Python中变量是指向对象的引用:

x = 3
print(id(x))  # 查看内存地址
x += 6        # 创建新对象,id(x)改变

重要is比较id(身份),==比较值。

二、典型例题解析

例题1:计算个位十位交换

# 将两位数13变成31
x = 13
result = (x % 10) * 10 + x // 10  # 3*10 + 1 = 31

例题2:表达式 x = 3==3, 5 的值是?

# 逗号表达式,先算3==3得True,再与5组成元组
x = (True, 5)  # D选项正确

例题3:与 x == 0 等价的表达式?

not x  # 当x为0或空值时为True

三、编程练习

题目:输入三位以上整数,输出百位以上数字(如1234输出12)

x = input('请输入3位以上的数字:')
if len(x) >= 3:
    x = int(x)
    print(x // 100)
else:
    print('输入错误。')

第二讲 Python控制结构

一、核心知识点

1. 语句块与缩进

Python通过缩进对齐区分语句块,通常使用4个空格。

2. 赋值语句
形式 说明 示例
链式赋值 多个变量同值 x = y = z = 6
序列解包 多变量并行赋值 x, y = y, x(交换)
复合赋值 运算后赋值 x += 1, x //= 2

重要x /= x*y+z 等价于 x = x / (x*y+z)

3. 输入输出格式化

print函数

print('AAA', "BBB", sep='-', end='!')  # 输出:AAA-BBB!

format方法

"Name:{:6s},Num:{:8d}".format('Joe', 10152)
# 输出:Name:Joe   ,Num:   10152
# {:6s} 字符串左对齐,占6位
# {:8d} 整数右对齐,占8位

%格式化

print("%+04d,%2.1f" % (25, 123.567))  # +025,123.6
# %+04d:带符号,补零,4位整数
# %2.1f:总宽2,1位小数
4. range函数
list(range(1, 10, 3))   # [1, 4, 7]  起始1,终止10(不含),步长3
list(range(-3, 21, 3))  # 循环8次:-3, 0, 3, 6, 9, 12, 15, 18
5. 条件表达式(三元运算符)
c = a if a > b else b  # 如果a>b则c=a,否则c=b
c = a if a else b      # 如果a非零则c=a,否则c=b
6. 逻辑运算符短路特性
2 > 1 and 1 - 1.0 and 'hello'  # 结果为0.0
# 2>1为True,继续;1-1.0=0.0(假值),返回0.0,不再执行'hello'

二、典型例题解析

例题1ans='n',表达式 ans=='y' or 'Y' 的值?

# 先算ans=='y'得False,再算False or 'Y',返回'Y'(非空字符串为真)

例题2x = y == 5 执行后x的值?

# 先算y==5得False,再赋值给x,x=False

三、编程练习

题目1:因式分解(小于1000的整数)

def factorize(n):
    print(f"{n}=", end="")
    first = True
    d = 2
    while d * d <= n:
        while n % d == 0:
            if not first:
                print("×", end="")
            print(d, end="")
            n //= d
            first = False
        d += 1
    if n > 1:
        if not first:
            print("×", end="")
        print(n, end="")
    print()

# 示例:factorize(60) 输出 60=2×2×3×5

题目2:统计字符串中各类字符个数

s = input("Please input a string:")
capital = little = digit = other = 0
for i in s:
    if 'A' <= i <= 'Z':
        capital += 1
    elif 'a' <= i <= 'z':
        little += 1
    elif '0' <= i <= '9':
        digit += 1
    else:
        other += 1
print("The result is:", (capital, little, digit, other))

题目3:1元换硬币(1分、2分、5分)

count = 0
for y in range(51):      # 2分硬币0-50个
    for z in range(21):  # 5分硬币0-20个
        x = 100 - 2*y - 5*z  # 1分硬币个数
        if x >= 0:
            print(f"x={x},y={y},z={z}")
            count += 1
print(f"There are {count} methods.")

题目4:判断素数

import math
x = eval(input('请输入一个自然数:'))
if x < 2:
    print("NO")
else:
    k = int(math.sqrt(x))
    for i in range(2, k + 2):
        if x % i == 0:
            print("NO")
            break
    else:  # for循环正常结束(未break)
        print("YES")

第三讲 字符串与正则表达式

一、核心知识点

1. 字符串索引与切片

s = 'abcdefg'

表达式 结果 说明
s[3] 'd' 索引从0开始
s[3:5] 'de' 切片[3,5)
s[:5] 'abcde' 从头开始到5
s[-1:1:-2] 'gec' 从尾到头,步长-2
s[-2:-5] '' 方向错误,空字符串
s[::-1] 'gfedcba' 反转字符串
2. 字符串常用方法
方法 功能 示例
upper() 转大写 'red hat'.upper()'RED HAT'
swapcase() 大小写互换 'PyThOn'.swapcase()'pYtHoN'
title() 单词首字母大写 'red hat'.title()'Red Hat'
replace(old,new) 替换 'red hat'.replace('hat','cat')
split(sep) 分割 'a,b,c'.split(',')['a','b','c']
rsplit(sep,1) 从右分割1次 'a,b,c'.rsplit(',',1)['a,b','c']
partition(sep) 三分割 'a,b,c'.partition(',')('a',',','b,c')
join(iter) 连接 ':'.join('abc')'a:b:c'
strip(chars) 去除两端字符 'abc'.strip('ac')'b'
find(sub,start,end) 查找子串位置 "Don't go out!".find('o',2,20)7
3. 字符串判断方法
方法 功能
isalpha() 是否全字母
isdigit() 是否全数字
isalnum() 是否字母或数字
isspace() 是否全空白
startswith() 是否以某子串开头
endswith() 是否以某子串结尾
4. 正则表达式(re模块)

常用函数

  • re.match(pattern, string):从字符串开头匹配
  • re.search(pattern, string):搜索整个字符串
  • re.findall(pattern, string):找到所有匹配
  • re.split(pattern, string):按匹配分割
  • re.sub(pattern, repl, string):替换

常用模式

模式 含义
. 任意字符(除\n)
\d 数字
\w 字母数字下划线
\s 空白字符
^ 字符串开头
$ 字符串结尾
* 0次或多次
+ 1次或多次
? 0次或1次
{n,m} n到m次
[] 字符集
() 分组

例题解析

  1. '^[A-Za-z]\w{3,8}$':以字母开头,后跟3-8个\w字符,总长度4-9位
  2. re.search(r'(\d{3,4})-(\d{7,8})', '0535-1234567').group(2)'1234567'
  3. re.sub('\w+','***','www.baidu.com')'***.baidu.com'(\w不匹配.)

二、编程练习

题目1:找出长度为3的单词

import re
text = input("请输入一段英文:")
words = re.findall(r'\b[a-zA-Z]{3}\b', text)
print(words)

题目2:验证Email地址

import re
pattern = r'^[a-zA-Z0-9]{1,10}@[a-zA-Z0-9]{1,10}\.(com|org)$'
email = input("请输入Email:")
if re.match(pattern, email, re.I):
    print("格式正确")
else:
    print("格式错误")

题目3:纠正单独的"i"为"I"

# 方法1:字符串处理
text = "i am a teacher,i am man, and i am 38 years old.I am not a businessman"
result = text.replace("i ", "I ").replace("i ", "I ")
print(result)

# 方法2:正则表达式
import re
result = re.sub(r'\bi\b', 'I', text)
print(result)

题目4:找出元音开头且长度≤3的单词

import re
text = "Ami put one apple and two oranges on the table."
# 方法1:一般处理
vowels = 'aeiouAEIOU'
words = text.split()
result = [w for w in words if w[0] in vowels and len(w) <= 3]

# 方法2:正则表达式
result = re.findall(r'\b[aeiouAEIOU]\w{0,2}\b', text)
print(result)  # ['Ami', 'one', 'and', 'on']

第四讲 列表与元组

一、核心知识点

1. 列表基本操作
操作 说明 示例
L[i] 索引访问 L[0]
L[start:end:step] 切片 L[::2] 每两个取一个
L.append(x) 末尾添加元素 L.append(5)
L.extend(iter) 扩展列表 L.extend([1,2])
L.insert(i,x) 插入 L.insert(0,'a')
L.remove(x) 删除首个x L.remove(3)
L.pop([i]) 弹出(默认末尾) L.pop()
L.sort() 原地排序 L.sort(reverse=True)
sorted(L) 返回新排序列表 不改变原列表
L.reverse() 原地反转
L.index(x) 查找索引
L.count(x) 计数
2. 列表解析式(列表推导)
# 基本形式
[x for x in range(10)]           # [0,1,2,...,9]
[x for x in range(21) if x%2==0] # 20以内偶数
[i for i in range(100) if i%13==0] # 100以内13的倍数
[5 for x in range(10)]           # 10个5
3. 深浅拷贝
x = [1,2,3,4,5]
y = x       # 引用同一对象,id相同
z = x[:]    # 浅拷贝,创建新对象,id不同
w = x.copy() # 浅拷贝

关键区别

  • y = x:y和x指向同一列表,修改互相影响
  • y = x[:]:创建新列表,修改互不影响
4. += 与 + 的区别
x = [1,2]
y = x
y += [3,4]   # 原地修改,x也变为[1,2,3,4]
# vs
y = y + [3,4] # 创建新列表,x仍为[1,2]
5. 元组特性
  • 不可变序列,用()定义
  • 单元素元组:(1,) 必须加逗号
  • tuple(range(2,10,2))(2, 4, 6, 8)

二、典型例题解析

例题1[3] in [1,2,3,4] 的值?

False  # [3]是列表,[1,2,3,4]中元素是整数,不包含列表[3]

例题2max((1,2,3)*2) 的值?

(1,2,3)*2(1,2,3,1,2,3)max3

例题3:矩阵对角线元素乘积

a = [[1,2,3],[4,5,6],[7,8,9]]
p = 1
for i in range(len(a)):
    p *= a[i][i]  # 1*5*9 = 45

三、编程练习

题目1:生成50个随机数,删除奇数

import random
x = [random.randint(1,100) for i in range(50)]
x = [num for num in x if num % 2 == 0]  # 保留偶数
print(x)

题目2:水果列表格式化输出

fruits = []
while True:
    f = input("输入水果名称(空行结束):")
    if f == "":
        break
    fruits.append(f)

if len(fruits) == 1:
    print(f"My favourite fruit is: {fruits[0]}")
elif len(fruits) > 1:
    result = ", ".join(fruits[:-1]) + ", and " + fruits[-1]
    print(f"My favourite fruits are: {result}")

题目3:提取子列表

x = eval(input('Please input a list:'))
start, end = eval(input('Please input start and end position:'))
print(x[start:end+1])

题目4:偶数下标降序排列,奇数下标不变

x = [random.randint(1,100) for i in range(20)]
# 提取偶数下标元素,排序后放回原位
even_indices = x[::2]
even_indices.sort(reverse=True)
x[::2] = even_indices
print(x)

题目5:前10升序,后10降序,中间不变

import random
x = [random.randint(1,100) for i in range(30)]
x[:10] = sorted(x[:10])
x[-10:] = sorted(x[-10:], reverse=True)
print(x)

第五讲 字典与集合

一、核心知识点

1. 字典(dict)
  • 键值对集合,键必须唯一且不可变(数字、字符串、元组)

  • 创建方式:

    d = {}  # 空字典
    d = {'a':1, 'b':2}
    d = dict(zip(keys, values))
    d = dict([('a',1), ('b',2)])
    

常用方法

方法 功能
d.get(k, default) 安全获取值
d.keys() 所有键
d.values() 所有值
d.items() 所有键值对
d.update(d2) 更新字典
d.pop(k) 删除并返回
del d[k] 删除键值对
2. 集合(set)
  • 无序、不重复元素集
  • 创建:s = {1,2,3}s = set([1,2,2,3]){1,2,3}
  • 不可变集合:frozenset()

集合运算

运算符 方法 含义
& intersection() 交集
| union() 并集
- difference() 差集
^ symmetric_difference() 对称差集

示例

{1,2,3,4} & {3,4,5}      # {3,4}
{1,2,3,4} | {3,4,5}      # {1,2,3,4,5}
{1,2,3,4} - {3,4,5}      # {1,2}
3. 可变与不可变
  • s1.update(s2):将s2元素添加到s1(原地修改)
  • s1.union(s2):返回新集合,s1不变

二、典型例题解析

例题1sum(set([1,2,2,3,3,3,4,4,4,4])) = 1+2+3+4 = 10

例题2:字典创建

dict([2,5],[3,4])      # 错误!dict()参数错误
dict(([1,2],[3,4]))    # 正确:{1:2, 3:4}

例题3d2 = d1 vs d2 = dict(d1)

# 程序一:d2=d1,指向同一对象,修改互相影响,sum=12
# 程序二:d2=dict(d1),创建新对象,互不影响,sum=7

三、编程练习

题目1:安全访问字典

d = {1:'a', 2:'b', 3:'c', 4:'d'}
key = eval(input('Please input a key:'))
print(d.get(key, '您输入的键不存在'))

题目2:学生成绩统计

n = int(input("请输入学生人数:"))
scores = {}
for i in range(n):
    name = input("姓名:")
    score = float(input("C语言成绩:"))
    scores[name] = score

if scores:
    max_score = max(scores.values())
    min_score = min(scores.values())
    avg_score = sum(scores.values()) / len(scores)
    max_student = [k for k,v in scores.items() if v == max_score]
    
    print(f"最高分:{max_score},最低分:{min_score},平均分:{avg_score:.2f}")
    print(f"最高分学生:{', '.join(max_student)}")

题目3:字典实现计算器

def calc(a, b, op):
    operations = {
        '+': a + b,
        '-': a - b,
        '*': a * b,
        '/': a / b if b != 0 else '除零错误'
    }
    return operations.get(op, '无效运算符')

a = float(input("第一个数:"))
b = float(input("第二个数:"))
op = input("运算符(+,-,*,/):")
print(calc(a, b, op))

题目4:去重并求最值

def unique_max_min(*args):
    s = set(args)
    print(f"去重后:{s}")
    if s:
        print(f"最大数:{max(s)},最小数:{min(s)}")

unique_max_min(1,2,3,2,1,5,3)

第六讲 函数与模块

一、核心知识点

1. 函数定义与调用
def 函数名(参数列表):
    """文档字符串"""
    函数体
    return 返回值  # 可选,无return返回None
2. 参数类型
参数类型 说明 示例
位置参数 按位置传递 def f(a,b):
默认参数 有默认值 def f(a, b=100):
关键字参数 按名称传递 f(b=10, a=20)
可变长度参数 *args接收元组 def f(*args):
关键字可变参数 **kwargs接收字典 def f(**kwargs):

重要警告:默认参数如果是可变对象,会保留修改!

def fun(a, b=[]):
    b.append(a)
    return a, b

print(fun(10))   # (10, [10])
print(fun(20,20)) # (40, [10, 20, 40])  # b保留了之前的值!
3. 变量作用域
关键字 作用
global 声明全局变量
nonlocal 声明外层非全局变量
4. 匿名函数(lambda)
f = lambda x, y: x*2 + y
f([4], [3])  # [4,4,3]  # 列表*2是复制,+是连接
5. 装饰器
@decorator  # 语法糖
def func():
    pass

# 等价于
func = decorator(func)

多重装饰器:由内向外执行(离函数最近的先执行)

6. 模块
  • __name__:模块名称
  • 单独运行时__name__ == '__main__'
  • 被导入时__name__为模块名

二、典型例题解析

例题1x += 1 vs x = x + 1 在函数内的区别

# 函数内x=0创建局部变量,如果在赋值前引用会报错
# 使用global x声明后,可以修改全局变量

例题2return [1,2,3], 4 返回 ([1,2,3], 4) 元组

三、编程练习

题目1:求奇数和与个数

def findOdd(*lst):
    odd_nums = [x for x in lst if x % 2 == 1]
    return sum(odd_nums), len(odd_nums)

s, c = findOdd(1,2,3,4,5,6,7)
print(f"奇数和:{s},个数:{c}")

题目2:接收关键字参数,返回最大值

def max_value(**kwargs):
    if kwargs:
        return max(kwargs.values())
    return None

print(max_value(a=10, b=20, c=5))  # 20

题目3:模拟sorted函数

def mySorted(iterable, reverse=False):
    lst = list(iterable)
    n = len(lst)
    for i in range(n):
        for j in range(0, n-i-1):
            if (lst[j] > lst[j+1]) != reverse:
                lst[j], lst[j+1] = lst[j+1], lst[j]
    return lst

print(mySorted([3,1,4,1,5,9,2,6]))
print(mySorted([3,1,4,1,5,9,2,6], reverse=True))

题目4:列表左移

def trans(lst, k):
    k = k % len(lst)  # 处理k大于长度的情况
    return lst[k:] + lst[:k]

print(trans([1,2,3,4,5], 2))  # [3,4,5,1,2]

题目5:哥德巴赫猜想(偶数=两个素数之和)

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

def goldbach(even):
    if even <= 2 or even % 2 == 1:
        return
    for i in range(2, even//2 + 1):
        if is_prime(i) and is_prime(even - i):
            print(f"{even} = {i} + {even-i}")

goldbach(100)

第七讲 面向对象程序设计

一、核心知识点

1. 类与对象
class 类名:
    类属性 =# 公有属性
    __私有属性 =# 私有属性(名前加__)
    
    def __init__(self, 参数):  # 构造方法
        self.实例属性 =# 实例属性
    
    def __del__(self):  # 析构方法
        pass
    
    def 方法名(self, 参数):  # 实例方法
        pass

# 创建对象
对象 = 类名(参数)
2. 类属性 vs 实例属性
类型 定义位置 访问方式 特点
类属性 类体内 类名.属性对象.属性 所有实例共享
实例属性 __init__中,带self. 对象.属性 每个实例独立
3. 继承
class 子类(父类):
    def __init__(self, 参数):
        super().__init__(参数)  # 调用父类构造
        # 或 父类.__init__(self, 参数)
        self.新属性 =

方法重写:子类重新定义父类方法

4. 面向对象三大特征
  1. 封装:通过访问控制(公有/私有)隐藏实现细节
  2. 继承:复用现有类的代码
  3. 多态:同一消息不同对象产生不同行为(方法重写)
5. 特殊方法
方法 用途
__init__ 构造对象
__del__ 销毁对象
__str__ 字符串表示
__repr__ 官方字符串表示
__eq__ == 运算符
__lt__ < 运算符

二、典型例题解析

例题1

class Account:
    def __init__(self, id):
        self.id = id  # 实例属性
        id = 888      # 局部变量,不影响self.id

acc = Account(100)
print(acc.id)  # 100

例题2

class parent:
    def __init__(self, param):
        self.v1 = param

class child(parent):
    def __init__(self, param):
        parent.__init__(self, param)  # 显式调用父类构造
        self.v2 = param

obj = child(100)
print(obj.v1, obj.v2)  # 100 100

三、编程练习

题目1:员工管理系统

class Employee:
    def __init__(self, name, id, dept, password):
        self.name = name
        self.id = id
        self.dept = dept
        self.__password = password
    
    def view_info(self):
        return f"姓名:{self.name},工号:{self.id},部门:{self.dept}"
    
    def change_password(self, old, new):
        if old == self.__password:
            self.__password = new
            return True
        return False

class Admin(Employee):
    def __init__(self, name, id, dept, password):
        super().__init__(name, id, dept, password)
    
    def view_employee(self, emp):
        return emp.view_info()
    
    def reset_password(self, emp):
        emp.__password = "000000"  # 实际需通过方法修改
        return True

题目2:工资计算系统

class Worker:
    def __init__(self, name, level):
        self.name = name
        self.level = level
    
    def calculate_salary(self):
        if self.level >= 10:
            return 10000
        elif self.level >= 8:
            return 8000
        else:
            return 5000

class Engineer:
    def __init__(self, name, degree, title):
        self.name = name
        self.degree = degree
        self.title = title
    
    def calculate_salary(self):
        if self.degree == "硕士" or self.title == "高工":
            return 10000
        elif self.degree == "本科" or self.title == "工程师":
            return 8000
        else:
            return 5000

第八讲 文件操作

一、核心知识点

1. 文件类型
  • 文本文件:以字符为单位存储(.txt, .py)
  • 二进制文件:以字节为单位存储(.jpg, .exe)
2. 文件打开模式
模式 说明
'r' 只读(默认)
'w' 只写,覆盖原有内容
'a' 追加写
'x' 创建新文件,已存在则失败
'b' 二进制模式
'+' 读写模式
'r+' 读写,文件必须存在
'w+' 读写,覆盖或创建
3. 文件操作方法
方法 功能
read(size) 读取size字节/字符,默认全部
readline() 读取一行
readlines() 读取所有行,返回列表
write(string) 写入字符串
writelines(list) 写入多行
seek(offset, whence) 移动文件指针
tell() 返回当前位置
close() 关闭文件

seek参数

  • seek(0):文件开头
  • seek(0, 1):当前位置
  • seek(0, 2):文件末尾
4. with语句(上下文管理器)
with open('file.txt', 'r') as f:
    content = f.read()
# 自动关闭文件,即使发生异常

二、编程练习

题目1:创建文件并读写

fp = open('d:\\test.txt', 'w+')
fp.write('Python is an useful language!\nI like Python!')
fp.seek(0)
ls = fp.readlines()
print(ls)
fp.close()

题目2:统计元音字母

def count_vowels(filename):
    vowels = 'aeiouAEIOU'
    count = 0
    with open(filename, 'r') as f:
        content = f.read()
        for char in content:
            if char in vowels:
                count += 1
    return count

print(count_vowels('Pythonfile1.txt'))

题目3:逐行统计(使用readline)

def count_vowels_line(filename):
    vowels = 'aeiouAEIOU'
    count = 0
    with open(filename, 'r') as f:
        while True:
            line = f.readline()
            if not line:  # 空串表示文件结束
                break
            for char in line:
                if char in vowels:
                    count += 1
    return count

题目4:输入字符串写入文件

# 写入直到输入*
with open('Pythonfile3.txt', 'w') as f:
    while True:
        s = input("输入字符串(*结束):")
        if s == '*':
            break
        f.write(s + '\n')

# 读出显示
with open('Pythonfile3.txt', 'r') as f:
    for line in f:
        print(line.strip())

题目5:追加写入

# 追加模式
with open('Pythonfile3.txt', 'a') as f:
    while True:
        s = input("输入字符串(*结束):")
        if s == '*':
            break
        f.write(s + '\n')

题目6:快递信息处理

import re

def save_info():
    name = input("姓名:")
    phone = input("手机号:")
    address = input("地址:")
    
    if not re.match(r'^\d{11}$', phone):
        print("手机号码格式不正确")
        return
    
    with open('Information.txt', 'w') as f:
        f.write(f"{name},{phone},{address}")
    print("信息已保存")

def read_info():
    try:
        with open('Information.txt', 'r') as f:
            name, phone, address = f.read().strip().split(',')
            masked_phone = '*' * 7 + phone[7:]
            print(f"姓名:{name}")
            print(f"手机号:{masked_phone}")
            print(f"地址:{address}")
    except FileNotFoundError:
        print("文件不存在")

save_info()
read_info()

第九讲 异常处理

一、核心知识点

1. 异常处理结构
try:
    # 可能引发异常的代码
except 异常类型1 as e:
    # 处理异常1
except 异常类型2:
    # 处理异常2
except:  # 捕获所有其他异常
    # 处理其他异常
else:
    # 无异常时执行
finally:
    # 无论是否异常都执行
2. 常见异常类
异常类 触发条件
ZeroDivisionError 除零
ValueError 值错误(如int(‘abc’))
TypeError 类型错误
IndexError 索引越界
KeyError 字典键不存在
FileNotFoundError 文件不存在
NameError 变量未定义
AttributeError 属性不存在
Exception 所有异常的基类
3. 主动引发异常
raise 异常类("错误信息")
raise ValueError("数值不能为负")
4. 断言
assert 条件, "错误信息"
# 条件为False时引发AssertionError

二、典型例题解析

例题1:异常匹配顺序

try:
    print(2/'0')  # TypeError:字符串不能做除数
except ZeroDivisionError:
    print('AAA')  # 不匹配
except Exception:  # 捕获所有异常
    print('BBB')  # 输出BBB

例题2:主动引发异常

x = 10
raise Exception("AAA")  # 程序终止,输出 Exception: AAA
x += 10  # 不会执行

三、编程练习

题目1:成绩不能为负(两种方式)

# 方式1:主动引发异常
scores = eval(input('请输入学生成绩,以逗号隔开:'))
for i in range(len(scores)):
    if scores[i] < 0:
        raise Exception('成绩不能为负!')
print(scores)

# 方式2:断言
for i in range(len(scores)):
    assert scores[i] >= 0, '成绩不能为负!'

题目2:自定义异常类

class NumberError(Exception):
    def __init__(self, value):
        self.value = value
        super().__init__(f"成绩{value}为负数!")

def check_score(score):
    if score < 0:
        raise NumberError(score)
    return score

try:
    s = float(input("输入成绩:"))
    print(check_score(s))
except NumberError as e:
    print(e)

题目3:三角形判断(使用断言)

def triangle_type(a, b, c):
    # 断言检查
    assert isinstance(a, int) and isinstance(b, int) and isinstance(c, int), "必须为正整数"
    assert a > 0 and b > 0 and c > 0, "边长必须为正"
    assert a + b > c and a + c > b and b + c > a, "不能构成三角形"
    
    if a == b == c:
        return "等边三角形"
    elif a == b or b == c or a == c:
        return "等腰三角形"
    else:
        return "一般三角形"

try:
    a, b, c = map(int, input("输入三边(空格分隔):").split())
    print(triangle_type(a, b, c))
except AssertionError as e:
    print(f"断言错误:{e}")

题目4:密码强度检查

import re

class PasswordError(Exception):
    pass

def check_password(pwd):
    if len(pwd) < 8 or len(pwd) > 12:
        raise PasswordError("密码长度必须为8-12位")
    if not re.match(r'^[a-zA-Z0-9_]+$', pwd):
        raise PasswordError("密码只能包含字母、数字和下划线")
    return True

try:
    pwd = input("设置密码:")
    check_password(pwd)
    print("密码设置成功")
except PasswordError as e:
    print(f"密码错误:{e}")

第十讲 图形用户界面设计

一、核心知识点

1. tkinter基础
import tkinter as tk

root = tk.Tk()          # 创建主窗口
root.title("窗口标题")   # 设置标题
root.geometry("400x300") # 设置大小

# 创建控件
label = tk.Label(root, text="Hello")
label.pack()            # 布局

root.mainloop()         # 进入主循环
2. 几何布局管理器
管理器 特点
pack() 简单,按顺序排列
grid() 网格布局,行列定位
place() 绝对或相对定位
3. 常用控件
控件 类名 用途
标签 Label 显示文本或图像
按钮 Button 点击触发事件
文本框 Entry 单行输入
多行文本 Text 多行输入
单选按钮 Radiobutton 多选一
复选框 Checkbutton 多选多
列表框 Listbox 列表选择
框架 Frame 容器
4. 事件绑定
def callback(event):
    print("事件发生")

# 方式1:控件绑定
widget.bind('<Button-1>', callback)  # 鼠标左键点击
widget.bind('<Key>', callback)       # 键盘事件

# 方式2:命令绑定
button = tk.Button(root, text="点击", command=callback)

# 常见事件
# <Button-1>:鼠标左键
# <Button-3>:鼠标右键
# <Double-Button-1>:双击
# <KeyPress-Return>:回车键
# <Motion>:鼠标移动

二、GUI设计步骤

  1. 创建主窗口root = tk.Tk()
  2. 添加控件:创建所需控件并设置属性
  3. 布局管理:使用pack/grid/place排列控件
  4. 事件绑定:为控件绑定处理函数
  5. 进入主循环root.mainloop()

三、编程示例

示例1:简单登录界面

import tkinter as tk
from tkinter import messagebox

def login():
    user = entry_user.get()
    pwd = entry_pwd.get()
    if user == "admin" and pwd == "123":
        messagebox.showinfo("成功", "登录成功")
    else:
        messagebox.showerror("失败", "用户名或密码错误")

root = tk.Tk()
root.title("登录系统")
root.geometry("300x150")

tk.Label(root, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
entry_user = tk.Entry(root)
entry_user.grid(row=0, column=1, padx=5, pady=5)

tk.Label(root, text="密码:").grid(row=1, column=0, padx=5, pady=5)
entry_pwd = tk.Entry(root, show="*")
entry_pwd.grid(row=1, column=1, padx=5, pady=5)

tk.Button(root, text="登录", command=login).grid(row=2, column=0, columnspan=2, pady=10)

root.mainloop()

示例2:温度转换器

import tkinter as tk

def convert():
    try:
        c = float(entry_c.get())
        f = c * 9/5 + 32
        label_result.config(text=f"{c}°C = {f:.2f}°F")
    except ValueError:
        label_result.config(text="请输入有效数字")

root = tk.Tk()
root.title("温度转换器")

tk.Label(root, text="摄氏度:").pack()
entry_c = tk.Entry(root)
entry_c.pack()

tk.Button(root, text="转换", command=convert).pack()

label_result = tk.Label(root, text="")
label_result.pack()

root.mainloop()

附录:重点速查表

1. 常用内置函数速查

函数 功能 示例
abs(x) 绝对值 abs(-5)5
all(iter) 所有元素为真 all([1,2,3])True
any(iter) 任一元素为真 any([0,1,0])True
bin(x) 转二进制字符串 bin(10)'0b1010'
chr(i) ASCII转字符 chr(65)'A'
ord(c) 字符转ASCII ord('A')65
divmod(a,b) 商和余数 divmod(10,3)(3,1)
enumerate(iter) 枚举索引值 list(enumerate('ab'))[(0,'a'),(1,'b')]
filter(func,iter) 过滤 list(filter(lambda x:x>0, [-1,1,2]))
map(func,iter) 映射 list(map(str, [1,2,3]))['1','2','3']
zip(*iters) 并行迭代 list(zip([1,2],['a','b']))[(1,'a'),(2,'b')]

2. 列表方法速查

方法 功能 时间复杂度
append(x) 末尾添加 O(1)
pop() 弹出末尾 O(1)
pop(0) 弹出首部 O(n)
insert(i,x) 插入 O(n)
remove(x) 删除首个x O(n)
index(x) 查找索引 O(n)
sort() 排序 O(n log n)
reverse() 反转 O(n)

3. 字符串格式化速查

# %格式化
"%s %d %f" % ("str", 10, 3.14)
"%5.2f" % 3.14159   # ' 3.14'(总宽5,2位小数)
"%-10s" % "hi"      # 左对齐
"%05d" % 42         # '00042'(补零)

# format方法
"{} {}".format("a", "b")
"{0} {1} {0}".format("a", "b")  # 位置引用
"{name}={value}".format(name="x", value=10)  # 关键字
"{:>10}".format("hi")   # 右对齐,宽10
"{:.2f}".format(3.1415) # 3.14

# f-string(Python 3.6+)
name = "Tom"
age = 20
f"{name} is {age} years old"
f"{3.14159:.2f}"

4. 常见错误与解决

错误类型 常见原因 解决方法
IndentationError 缩进不一致 统一使用4空格或Tab
SyntaxError 语法错误 检查冒号、括号匹配
NameError 变量未定义 检查变量名拼写
TypeError 类型不匹配 检查操作数类型
IndexError 索引越界 检查索引范围
KeyError 字典键不存在 使用get()方法
ValueError 值错误 检查输入格式
ZeroDivisionError 除零 添加除零检查
FileNotFoundError 文件不存在 检查路径

学习建议

  1. 理解概念:重点掌握Python的引用语义、可变/不可变对象
  2. 动手实践:每个知识点都要编写代码验证
  3. 对比记忆:如is vs ==list vs tupledeepcopy vs copy
  4. 关注细节:如列表解析式的执行顺序、默认参数的陷阱
  5. 综合应用:将各章节知识结合解决实际问题
Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐