Javaer快速掌握Python笔记
type
函数
a = 100
b = 123.45
c = 'hello, world'
d = True
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'bool'>
输入 input()
变量 = input("提示信息:")
函数返回值类型是字符串
身份运算符:is
、is not
作用:
判断 两个变量是否引用同一个对象(内存地址是否相同)。
不是判断“值是否相等”,而是判断“是不是同一个对象”。
示例:
a = [1, 2, 3]
b = a
c = [1, 2, 3]print(a is b) # True → b 指向同一个对象
print(a is c) # False → 虽然值相等,但不是同一个对象
print(a == c) # True → 值相等
==
判断的是值是否相等
成员运算符:in
、not in
作用:
判断 某个元素是否存在于序列(字符串、列表、元组、字典、集合)中。
示例:
nums = [1, 2, 3, 4]
print(2 in nums) # True
print(5 not in nums) # Truetext = "hello"
print("h" in text) # True
print("z" in text) # Falsedic = {"name": "Tom", "age": 18}
print("name" in dic) # True (判断 key 是否存在)
print("Tom" in dic) # False (不判断 value)
注意
- 小整数缓存机制
Python 会缓存-5 ~ 256
的整数,所以:
a = 100b = 100print(a is b) # True → 实际上是同一个缓存对象
但:
a = 1000b = 1000print(a is b) # False → 超出缓存范围,不同对象
f-string
格式化
语法:
在字符串前加上 f
,直接在 {}
中写变量或表达式。
name = "小明"
age = 18
print(f"我叫 {name},今年 {age} 岁。")
输出:
我叫 小明,今年 18 岁。
match-case语句
基本语法:
match 变量:case 值1:执行语句1case 值2:执行语句2case _:默认执行语句(相当于 else)
✅ 关键点:
-
match
用来匹配一个表达式或变量; -
case
用来定义匹配的条件; -
_
表示通配符,即“其他情况”; -
匹配成功后,程序就不会继续往下匹配,不需要写
break
简单数字匹配:
command = input("请输入命令编号(1-3):")match command:case "1":print("启动系统")case "2":print("关闭系统")case "3":print("重启系统")case _:print("未知命令")
匹配多个值:
fruit = "apple"match fruit:case "apple" | "pear" | "peach":print("这是一种水果")case "carrot" | "potato":print("这是一种蔬菜")case _:print("未知食物")
进阶技巧:守卫(guard)条件:
你还可以在 case
后加上条件判断:
x = int(input("输入数字:"))match x:case n if n < 0:print("负数")case n if n == 0:print("零")case n if n > 0:print("正数")
列表(list
)总结
列表简介
- 特点:有序, 支持索引访问, 元素可以重复;支持动态扩展
创建列表
items1 = [35, 12, 99] # 使用 [] 创建
items2 = ['Python', 'Java']
items3 = [100, 12.3, 'Python', True]
items4 = list(range(1, 10)) # 使用 list() 构造器
items5 = list('hello')
列表运算
# 拼接
[1,2,3] + [4,5] # [1,2,3,4,5]
# 重复
[1,2] * 3 # [1,2,1,2,1,2]
# 成员判断
3 in [1,2,3] # True
4 not in [1,2,3] # True
索引与切片
- 索引访问:
fruits = ['apple','banana','peach']
fruits[0] # apple
fruits[-1] # peach
fruits[1] = 'orange'
- 切片访问:
fruits[0:2] # ['apple','orange']
fruits[:2] # ['apple','orange']
fruits[::2] # ['apple','peach']
fruits[-2::-1] # ['orange','apple']
- 切片修改:
fruits[0:2] = ['x','y'] # 修改指定区间的元素
添加元素
lst = [1,2,3]
lst.append(4) # [1,2,3,4]
lst.insert(1, 9) # [1,9,2,3,4]
删除元素
lst.remove(9) # 删除指定值,若不存在会报错
lst.pop() # 删除最后一个元素
lst.pop(1) # 删除指定索引元素
del lst[0] # 删除指定索引元素
lst.clear() # 清空列表
查询元素
lst.index(2) # 返回第一个匹配索引
lst.count(2) # 统计元素出现次数
排序与反转
lst.sort() # 升序排序
lst.reverse() # 元素顺序反转
列表遍历
- 通过索引遍历:
for i in range(len(lst)):print(lst[i])
- 直接遍历元素:
for item in lst:print(item)
切片
列表切片的语法为:
list[start:end:stride]
-
start:起始索引,表示从哪个位置开始取元素(包含该位置的元素)。
-
end:结束索引,表示取到哪个位置结束(不包含该位置的元素)。
-
stride:步长,表示索引每次增加的值(可以为负数表示反向取)。
注意:切片不会改变原列表,它返回的是一个新的列表。
正向切片
fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']# 从索引1取到索引3(不包含3)
print(fruits[1:3]) # ['banana', 'cherry']# 从索引0取到索引5,每次间隔2
print(fruits[0:5:2]) # ['apple', 'cherry', 'fig']# 从索引2取到最后
print(fruits[2:]) # ['cherry', 'date', 'fig', 'grape']# 从开始取到索引3(不包含3)
print(fruits[:3]) # ['apple', 'banana', 'cherry']# 取整个列表
print(fruits[:]) # ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
切片赋值(修改元素)
fruits = ['apple', 'banana', 'cherry', 'date', 'fig']# 修改索引1到3的元素
fruits[1:4] = ['blueberry', 'cranberry', 'dragonfruit']
print(fruits) # ['apple', 'blueberry', 'cranberry', 'dragonfruit', 'fig']# 删除部分元素
fruits[1:3] = []
print(fruits) # ['apple', 'dragonfruit', 'fig']# 插入元素
fruits[1:1] = ['banana', 'cherry']
print(fruits) # ['apple', 'banana', 'cherry', 'dragonfruit', 'fig']
字符串
s = 'hello'
print(s + ' world') # 拼接
print(s * 3) # 重复
print('h' in s) # True
print('a' > 'A') # True
索引与切片
-
索引:
s[i]
正向从 0 开始,负向从 -1 开始 -
切片:
s[start:end:step]
,返回新字符串,原字符串不变
s = 'abc123'
print(s[0], s[-1]) # a 3
print(s[1:4]) # bc1
print(s[::2]) # ac2
print(s[::-1]) # 321cba
- 注意:字符串不可变,不能通过索引直接修改字符。
遍历
for i in range(len(s)):print(s[i])for ch in s:print(ch)
常用字符串方法
功能 | 方法示例 | 说明 |
---|---|---|
大小写转换 | s.upper() / s.lower() / s.title() / s.capitalize() | 返回新字符串 |
查找 | s.find(sub), s.rfind(sub), s.index(sub) | 返回索引或 -1 / 异常 |
开头/结尾判断 | s.startswith('a'), s.endswith('b') | 返回 True/False |
特性判断 | s.isdigit(), s.isalpha(), s.isalnum() | 检查数字、字母、字母数字 |
修剪 | s.strip(), s.lstrip(), s.rstrip() | 去掉首尾指定字符 |
替换 | s.replace(old, new, count=-1) | 替换字符串 |
拆分/合并 | s.split(sep=None, maxsplit=-1), sep.join(list) | 拆分成列表或合并列表 |
格式化 | '{0} {1}'.format(a,b), f'{a} {b}' | 格式化字符串 |
对齐 | s.center(width, fill), s.ljust(width, fill), s.rjust(width, fill), s.zfill(width) | 居中、左/右对齐、补零 |
编码/解码 | s.encode(encoding), b.decode(encoding) | str ↔ bytes |
集合
特点: 无序,元素不能重复, 不支持索引运算
注意:空集合必须使用 set()
,{}
是空字典。
元素要求:必须是可哈希类型(int
、float
、str
、tuple
等),不可变类型;集合、列表等可变类型不能作为元素。
set1 = {1, 2, 3, 3, 3, 2}
print(set1)set2 = {'banana', 'pitaya', 'apple', 'apple', 'banana', 'grape'}
print(set2)set3 = set('hello')
print(set3)set4 = set([1, 2, 2, 3, 3, 3, 2, 1])
print(set4)set5 = {num for num in range(1, 20) if num % 3 == 0 or num % 7 == 0}
print(set5)
![[Pasted image 20251008190141.png]]
set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}# 交集
print(set1 & set2) # {2, 4, 6}
print(set1.intersection(set2)) # {2, 4, 6}# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 10}
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8, 10}# 差集
print(set1 - set2) # {1, 3, 5, 7}
print(set1.difference(set2)) # {1, 3, 5, 7}# 对称差
print(set1 ^ set2) # {1, 3, 5, 7, 8, 10}
print(set1.symmetric_difference(set2)) # {1, 3, 5, 7, 8, 10}
集合的方法:
set1 = {1, 10, 100}# 添加元素
set1.add(1000)
set1.add(10000)
print(set1) # {1, 100, 1000, 10, 10000}# 删除元素
set1.discard(10)
if 100 in set1:set1.remove(100)
print(set1) # {1, 1000, 10000}# 清空元素
set1.clear()
print(set1) # set()
元组
-
有序,可以存放多个元素。
-
元组是不可变类型,一旦创建,元素不可修改、删除或增加
-
可以包含任意类型的元素(整数、字符串、布尔值等)
t1 = (35, 12, 98) # 三元组 t2 = ('骆昊', 45, True, '四川成都') # 四元组t3 = 10, 20, 30 # 等价于 (10, 20, 30)print(type(t1)) # 输出:<class 'tuple'>
-
单元素元组需加逗号:
t = (5,)
-
不加逗号的括号不是元组,而是普通类型
-
-
基本操作
-
类型与长度
type(t1) # <class 'tuple'> len(t1) # 元素数量
-
索引运算
t1[0] # 第一个元素 t2[-1] # 最后一个元素
-
切片运算
t2[:2] # 从开头到索引2(不含) t2[::3] # 步长为3
-
-
遍历与成员运算
for elem in t1:print(elem)12 in t1 # True 'Hao' not in t2 # True
-
拼接与比较
-
拼接:
t3 = t1 + t2
,生成新的元组 -
比较:按元素逐一比较大小和相等性
t1 == t3 # False t1 >= t3 # False t1 <= (35, 11, 99) # False
-
字典
-
字典是一种无序的可变容器,以**键值对(key-value)**的形式保存数据。
-
通过键可以快速访问对应的值,非常适合存储关联数据(例如人的信息、商品信息等)。
-
键必须是不可变类型(如
int
、float
、str
、tuple
),值可以是任意类型(可变或不可变)。# 字面量语法 person = {'name': '王大锤', 'age': 55, 'height': 168}# 使用 dict 构造器 person = dict(name='王大锤', age=55, height=168)# 使用 zip 创建字典 items = dict(zip('ABCDE', range(1,6)))# 字典生成式 cubes = {x: x**3 for x in range(1,6)}
-
索引运算:通过键访问或修改值
person['age'] = 25person['tel'] = '13122334455'
- 成员运算:判断键是否存在
'name' in person # True'tel' in person # False
- 循环遍历:遍历字典的键,或用
items()
遍历键值对
for key, value in person.items():print(f'{key}: {value}')
字典方法:
- 获取值:
get
方法避免KeyError
person.get('age') # 25person.get('sex', '男') # '男'
- 获取键、值、键值对:
person.keys()person.values()person.items()
- 更新字典:
update
或|=
person.update({'age': 30, 'addr': '成都'})person |= {'age': 30, 'addr': '成都'}
- 删除元素:
pop
、popitem
、del
person.pop('age') # 返回被删除的值person.popitem() # 返回被删除的键值对del person['addr'] # 删除指定键person.clear() # 清空字典
空函数
空函数指的是没有实现功能,只是一个占位的函数。
有时候我们在写程序时,函数的具体实现还没想好,但又想先写好结构,这时就需要空函数。
例如:
def my_function():pass
pass
的作用
Python 不允许定义空代码块。
比如:
def func():# 什么都不写
这会报错:
IndentationError: expected an indented block
pass
就是用来防止语法错误的占位符
pass
是一个空语句,执行时什么也不做
# 示例1:空函数中使用 pass
def func():pass# 示例2:空类中使用 pass
class Student:pass# 示例3:空循环中使用 pass
for i in range(5):pass# 示例4:空条件中使用 pass
if True:pass
函数参数
默认参数
- 如果传了参数 → 使用传入的值
- 如果没传 → 使用默认值
def greet(name="游客"):print("你好,", name)greet() # 输出:你好, 游客
greet("小明") # 输出:你好, 小明
注意默认参数要放在普通参数之后:
def func(a, b=10): # ✅ 正确passdef func(b=10, a): # ❌ 错误pass
可变参数(*args
)
*args
可以接收 任意数量的位置参数,在函数内部是一个元组。
def show_numbers(*args):print(args)show_numbers(1, 2, 3)
# 输出:(1, 2, 3)
关键字参数(**kwargs
)
**kwargs
可以接收 任意数量的“键=值”形式参数,是一个字典
def show_info(**kwargs):print(kwargs)show_info(name="小明", age=18)
# 输出:{'name': '小明', 'age': 18}
面向对象
构造方法 __init__
构造方法名字固定为 __init__
:
class Student:def __init__(self, name, score):self.name = nameself.score = scorebart = Student("Bart", 59)
print(bart.name, bart.score) # Bart 59
实例方法
- 作用:普通的方法,需要通过对象调用,操作对象的属性, 第一个参数必须是
self
,表示当前对象本身。
class Student:def __init__(self, name, score):self.name = nameself.score = scoredef print_score(self):print(f"{self.name}: {self.score}")bart = Student("Bart", 59)
bart.print_score() # Bart: 59
类方法
- 装饰器:
@classmethod
, 第一个参数必须是cls
,表示当前类
class Student:count = 0 # 类属性def __init__(self, name):self.name = nameStudent.count += 1@classmethoddef print_count(cls):print(f"总共有 {cls.count} 个学生")s1 = Student("Bart")
s2 = Student("Lisa")
Student.print_count() # 总共有 2 个学生
静态方法
-
作用:既不操作对象属性,也不操作类属性。
-
装饰器:
@staticmethod
, 可以看作是类里面的普通函数,用类名或对象都能调用
class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 5)) # 8
访问限制
如果要让内部属性不被外部访问,可以在属性的名称前加两个下划线__
,就变成了一个私有变量
class Man: def __init__(self,name,age): self.__name=name self.__age=age def printInfo(self): print(self.__name+str(self.__age)) def getName(self): return self.__name def getAge(self): return self.__age
判断一个变量是否是某个类型可以用isinstance()
isinstance(a, list)
isinstance(1, int)
继承
class Parent:def __init__(self, name):self.name = namedef greet(self):print(f"Hello, I am {self.name}")# 子类继承父类
class Child(Parent):passc = Child("Alice")
c.greet() # Hello, I am Alice
异常处理
try…except
try:r = 10 / 0
except ZeroDivisionError as e:print('捕获到错误:', e)
-
try
:放置可能出错的代码 -
except
:捕获指定类型的异常 -
可以捕获多个异常:
try:r = int('abc') # ValueError
except ZeroDivisionError:print('除零错误')
except ValueError:print('值错误')
else
会在 没有异常发生时执行:
try:r = 10 / 2
except ZeroDivisionError:print('除零错误')
else:print('没有错误,结果:', r)
finally
无论是否发生异常都会执行,常用于释放资源:
try:f = open('test.txt')data = f.read()
except FileNotFoundError:print('文件不存在')
finally:print('关闭文件')f.close()
raise 抛出异常
- 用于 主动抛出异常,可以中断当前流程,让调用者处理。
def foo(x):if x == 0:raise ValueError("x 不能为 0")return 10 / xfoo(0) # 会抛出 ValueError
- 异常是对象,必须是 Exception 的子类。
logging 模块
logging
用于 记录日志,比print
更专业,适合生产环境。
import logginglogging.basicConfig(level=logging.INFO) # 配置日志等级logging.info("这是普通信息")
logging.warning("这是警告信息")
logging.error("这是错误信息")
-
日志等级从低到高:
DEBUG < INFO < WARNING < ERROR < CRITICAL
-
可以把日志输出到文件或终端。
将日志输出到文件
import logging # 创建 logger 对象
logger = logging.getLogger()
logger.setLevel(logging.INFO) # 创建文件处理器
file_handler = logging.FileHandler('app.log', mode='w', encoding='utf-8') # 创建控制台处理器
console_handler = logging.StreamHandler() # 设置统一格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter) # 将处理器添加到 loggerlogger.addHandler(file_handler)
logger.addHandler(console_handler) # 写日志
logger.info("这是普通信息")
logger.warning("这是警告信息")
logger.error("这是错误信息")
- 可以配置时间、日志等级、输出格式, 日志可长期保存,用于排查问题
with语句
用于 自动管理资源(比如文件、网络连接、锁等),避免手写繁琐的 try...finally
with open('data.txt', 'r') as f:data = f.read()print(data)
等价于:
f = open('data.txt', 'r')
try:data = f.read()print(data)
finally:f.close()
__name__
是什么
在每个 Python 文件中,解释器都会自动定义一个变量:它表示当前模块的名字。
__name__
-
如果这个文件是 被直接运行的脚本,那么:
__name__ == '__main__'
-
如果这个文件是 被其他模块导入的,那么:
__name__ == 模块名(文件名,不含 .py)
作用:
def main():print("程序的主入口")if __name__ == '__main__':main()
✅ 只有在该文件被“直接运行”时才会执行 main()
❌ 如果该文件被“import 导入”,不会执行。
文件操作
打开文件:open()
f = open("test.txt", "r", encoding="utf-8")
参数说明:
参数 | 作用 |
---|---|
文件名 | "test.txt" 要打开的文件名 |
模式 | "r" 代表读取模式(read) |
编码 | encoding="utf-8" 解决中文乱码问题 |
常见的打开模式:
模式 | 含义 |
---|---|
'r' | 只读模式(默认) |
'w' | 只写模式(会覆盖原内容) |
'a' | 追加模式(在原内容后面追加) |
'rb' | 以二进制方式读取(read binary) |
'wb' | 以二进制方式写入(write binary) |
读取文件内容
f = open("test.txt", "r", encoding="utf-8")
content = f.read() # 读取全部内容
print(content)f.seek(0) # 将文件指针移动到开头
line1 = f.readline() # 读取一行
lines = f.readlines() # 读取所有行,返回列表
f.close()
注意:
使用完文件后必须调用 f.close()
关闭,否则可能导致资源未释放或数据未保存。
写入文件
f = open("output.txt", "w", encoding="utf-8")
f.write("Hello, Python!\n")
f.write("写入第二行")
f.close()
如果文件不存在,
"w"
模式会创建一个新文件。
如果文件存在,内容会被清空后写入。
推荐写法:with open()
(自动关闭文件)
with open("test.txt", "r", encoding="utf-8") as f:for line in f:print(line.strip())
with
块结束后,Python 会自动关闭文件,不需要 f.close()
, 推荐用这个