python 基础
"""自定义异常类"""try:raise CustomError("自定义错误信息", 1001)print(f"错误代码 {e.code}: {e}")
·
1.条件判断
# 1.条件判断
a = 2
if a == 1:
print("1")
elif a == 2:
print("2")
else:
print("3")
2.循环
注意:什么是sequence,Sequence(序列) 是一种 有序的、可迭代的容器类型,其中的元素按照一定顺序存储,并且可以通过 索引(index) 访问。
Python 内置的常见序列类型包括:
字符串(
str
)
例如:
"hello"
列表(
list
)
例如:
[1, 2, 3]
元组(
tuple
)
例如:
(1, 2, 3)
范围(
range
)
例如:
range(5) 等价于[0,1,2,3,4],也可以是range[2,5]等价与[2,3,4],range是个左闭右开的区间。
for iterating_var in sequence:
statements(s)
# 2.循环
for num in range(10):
print(num)
3.while 循环
while 判断条件(condition):
执行语句(statements)……
# 3.while循环
str = "hello python"
i = 0
while i < len(str):
print(str[i])
i += 1
else:
print("end")
4. continue & break & pass
4.1 continue
表示跳过本次循环
4.2 break
表示跳出循环
4.3 pass
空语句,仅占位,可以用户代码块中,不只是循环中
5.number类型
# 5.number类型
a = 1;
b = 2;
print(max(a,b))
c = 0.1
print(int(c))
6.string类型
6.1 string基本
str1 = "hello python" #6.1 python的字符串和java一样是个不变量
print(str1[0]) #6.2 取出第一个岗位
print(str1[1:2]) #6.3 [1,2)也是左闭右开
# 6.4三引号表示是一个字符块
str2 = '''
你好
中国
'''
print(str2)
# 6.5 r""表示生字符串,\n这种转义字符不转义
print(r"你好\n")
# 6.6 f"{}"表示对里面的占位
i = 0
for i in range(10):
print(f"第{i}个")
6.2 string的内置函数
#1.大小写转换
print("aaa".upper()) #全转大写
print("bbb".lower()) #全转小写
print("hello word aa".title()) #首字母大写
#2.查找替换
print('hello'.find('l')) #查找l第一次出现的地方,没有找到放回-1
print("hi".replace("i", "ello")) #替换元素
#3.格式化
print(" hell ".strip()) #去除首尾空白字符
#4.拆分合并
print('1,2,3'.split(',')) #按照,拆分
print(','.join(["a","b","c"])) #按照,合并
#5. 判断
print("hello".startswith("he"))
#6.长度
print(len("hello"))
7. 列表类型
7.1 创建列表
empty_list = [] # 空列表
numbers = [1, 2, 3, 4] # 整数列表
mixed = [1, "hello", True] # 混合类型列表
nested = [[1, 2], [3, 4]] # 嵌套列表
7.2 访问元素
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 输出: "apple"(索引从0开始)
print(fruits[-1]) # 输出: "cherry"(负数索引从末尾开始)
7.3 添加元素
fruits.append("orange") # 末尾添加: ["apple", "blueberry", "cherry", "orange"]
fruits.insert(1, "mango") # 插入到索引1: ["apple", "mango", "blueberry", ...]
7.4 删除元素
fruits.pop() # 删除末尾元素并返回("orange")
fruits.pop(1) # 删除索引1的元素("mango")
fruits.remove("apple") # 删除第一个匹配的元素("apple")
del fruits[0] # 删除索引0的元素
7.5 切片操作
左闭右开区间
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # 输出: [1, 2, 3](索引1到3)
print(nums[:3]) # 输出: [0, 1, 2](从开头到索引2)
print(nums[3:]) # 输出: [3, 4, 5](索引3到末尾)
print(nums[::2]) # 输出: [0, 2, 4](步长为2)
print(nums[::-1]) # 输出: [5, 4, 3, 2, 1, 0](反转列表)
7.6 合并列表
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2 # [1, 2, 3, 4]
list1.extend(list2) # 扩展list1: [1, 2, 3, 4]
7.7 常用方法
nums = [1, 2, 3, 2]
print(len(nums)) # 长度: 4
print(nums.index(2)) # 第一个2的索引: 1
print(nums.count(2)) # 元素2出现的次数: 2
nums.reverse() # 反转列表: [2, 3, 2, 1]
nums.sort() # 排序: [1, 2, 2, 3]
7.8 列表推导式
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]
8.元组基本操作
8.1 特征
元组不可变,数据更加安全,并且可以用于字典值。
8.2 创建元组
# 空元组
empty_tuple = ()
# 单元素元组(注意末尾的逗号)
single_element = (42,)
# 多元素元组
colors = ("red", "green", "blue")
numbers = (1, 2, 3, 4, 5)
# 不加括号创建元组(元组打包)
coordinates = 10, 20, 30 # 等价于 (10, 20, 30)
8.3 访问元组
print(colors[0]) # 输出: "red"
print(numbers[-1]) # 输出: 5(最后一个元素)
print(coordinates[1:3]) # 输出: (20, 30)(切片操作)
8.4 元组解包
point = (3, 5)
x, y = point # 解包赋值
print(f"x={x}, y={y}") # 输出: x=3, y=5
# 扩展解包(Python 3.5+)
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # 1
print(middle) # [2, 3, 4](列表)
print(last) # 5
8.5 元组连接
tuple1 = (1, 2)
tuple2 = (3, 4)
combined = tuple1 + tuple2 # (1, 2, 3, 4)
8.6 元素重复
repeated = ("Hi",) * 3 # ("Hi", "Hi", "Hi")
8.7 元组常见方法
t = (1, 2, 3, 2, 4, 2)
print(t.count(2)) # 输出: 3(元素2出现的次数)
print(t.index(3)) # 输出: 2(元素3首次出现的索引)
9.字典
9.1 字典特征
键值对结构:每个元素由键(key)和值(value)组成
快速查找:基于键的哈希表实现,查找时间复杂度 O(1)
键唯一性:键必须是不可变类型(字符串、数字、元组等),且不能重复
值多样性:值可以是任意数据类型(包括列表、字典等)
9.2 创建字典
# 空字典
empty_dict = {}
# 直接创建
person = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Physics"]
}
# 使用 dict() 构造函数
coordinates = dict(x=10, y=20, z=30)
# 键值对列表转换
pairs = [("name", "Bob"), ("age", 25)]
person2 = dict(pairs)
9.3 访问字典
# 通过键访问
print(person["name"]) # 输出: Alice
# 使用 get() 方法(避免 KeyError)
print(person.get("age")) # 30
print(person.get("country")) # None
print(person.get("country", "USA")) # 设置默认值: USA
# 检查键是否存在
if "email" not in person:
person["email"] = "alice@example.com"
9.4 修改字典
# 添加/更新元素
person["age"] = 31 # 更新已有键
person["country"] = "Canada" # 添加新键
# 使用 update() 批量更新
person.update({"age": 32, "city": "Toronto"})
# 合并字典 (Python 3.9+)
combined = person | person2 # 新字典包含两者的键值
9.5 删除字典元素
# 删除指定键值对
del person["is_student"]
# 删除并返回值
email = person.pop("email") # 返回被删除的值
last_item = person.popitem() # 删除最后添加的键值对
# 清空字典
person.clear()
9.6 遍历字典
# 遍历所有键
for key in person.keys():
print(key)
# 遍历所有值
for value in person.values():
print(value)
# 遍历所有键值对
for key, value in person.items():
print(f"{key}: {value}")
# 字典推导式
squared = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
9.7 嵌套字典
类似java的嵌套元素
users = {
"alice": {
"age": 30,
"email": "alice@example.com"
},
"bob": {
"age": 25,
"email": "bob@example.com"
}
}
# 访问嵌套值
print(users["alice"]["email"]) # alice@example.com
10.python的异常处理机制
10.1 异常的基本用法
try:
# 可能引发异常的代码
result = 10 / 0
except ZeroDivisionError:
# 处理特定异常
print("不能除以零!")
except (TypeError, ValueError) as e:
# 处理多个异常类型
print(f"类型或值错误: {e}")
except Exception as e:
# 处理所有其他异常
print(f"发生未知错误: {e}")
else:
# 当没有异常发生时执行
print("计算成功完成!")
finally:
# 无论是否发生异常都会执行
print("清理资源...")
10.2 自定义异常
class CustomError(Exception):
"""自定义异常类"""
def __init__(self, message, code):
super().__init__(message)
self.code = code
try:
raise CustomError("自定义错误信息", 1001)
except CustomError as e:
print(f"错误代码 {e.code}: {e}")
11.python的文件io操作
11.1 基本操作
# 基本语法
file = open('filename', 'mode', encoding='utf-8') //mode如果是r表示只读,w表示写覆盖,a表示写追加,+表示读写
11.2 读取文件内容
# 一次性读取全部内容
with open('example.txt', 'r') as f:
content = f.read()
# 逐行读取
with open('example.txt', 'r') as f:
for line in f:
print(line.strip())
# 读取指定字节数
with open('largefile.bin', 'rb') as f:
chunk = f.read(1024) # 读取1KB
11.3 写入文件内容
# 写入字符串
with open('output.txt', 'w') as f:
f.write("Hello, World!\n")
f.write("第二行内容")
# 写入多行
lines = ["第一行", "第二行", "第三行"]
with open('output.txt', 'w') as f:
f.writelines(line + '\n' for line in lines)
11.4 文件指针操作
with open('data.txt', 'r+') as f:
# 获取当前位置
position = f.tell()
print(f"当前位置: {position}")
# 读取前10个字符
data = f.read(10)
# 移动到文件开头
f.seek(0)
# 在开头插入内容
f.write("插入的文本")
# 移动到文件末尾
f.seek(0, 2)
f.write("\n末尾添加的内容")
11.5 上下文管理with
使用with
语句处理文件,它可以自动关闭文件并处理异常:
try:
with open('file.txt', 'r') as f:
data = f.read()
# 文件在此处自动关闭
except FileNotFoundError:
print("文件不存在")
12. 目录操作
import os
import shutil
# 创建目录
os.mkdir('new_dir')
os.makedirs('path/to/nested/dir', exist_ok=True)
# 删除目录
os.rmdir('empty_dir')
shutil.rmtree('dir_with_content') # 递归删除
# 遍历目录
for root, dirs, files in os.walk('.'):
print(f"当前目录: {root}")
print(f"子目录: {dirs}")
print(f"文件: {files}")
# 文件信息
stats = os.stat('file.txt')
print(f"大小: {stats.st_size} 字节")
print(f"修改时间: {stats.st_mtime}")
13. json序列化
import json
# 写入 JSON
data = {"name": "Alice", "age": 30, "scores": [90, 85, 95]}
with open('data.json', 'w') as f:
json.dump(data, f, indent=2) #indent=2表示用两个空格进行间隔
# 读取 JSON
with open('data.json', 'r') as f:
loaded = json.load(f)
print(loaded['name']) # Alice
---------------------------------未完待续-----------------------------
更多推荐
所有评论(0)