Python 基础笔记
变量赋值
单变量赋值
name = '名字'
多变量赋值
name, age = '名字', 12
数据类型
查看变量类型
type(变量)
数字类型转换
int() # 转换为 int 类型
float() # 转换为 float 类型
运算符
** # 幂运算
// # 取整除
% # 取模
= # 赋值
布尔运算
and # 与运算 (&&)
or # 或运算 (||)
not # 非运算 (!)
字符串
字符串类型转换
str() # 转换为字符串
多行字符串
'''
多行字符串内容
保留格式
'''
字符串索引和切片
string[下标] # 索引
string[start:end] # 切片
字符串长度
len(string) # 获取字符串长度
字符串的方法:.strip()去除前后空格, .upper()返回大写 , .replace()替换 , .lower()返回小写, .split()按照指定分隔符分割, in,not in 检查是否在内 , +对字符拼接
列表
['a',1] 类似数组
创建列表
arr = ['a', 1, 2]
修改列表元素
arr[1:2] = [3, 4] # 多值修改
删除列表元素
del arr[0:2] # 删除指定范围的元素
arr.remove('a') # 删除指定元素
arr.pop(index) # 删除指定下标的元素,返回值为被删除的元素
增加列表元素
arr += [5, 6] # 尾部增加元素
arr.append(7) # 尾部增加单个元素
arr.insert(下标, [8, 9]) # 在指定位置插入元素
循环
for 循环
for i in sun_in_sky:
if i > 1:
print("继续射箭")
while 循环
i = 0
while i < 20:
i += 1
print(i)
if i % 2 != 0:
continue # 跳过本次循环
break # 退出循环
字典
{ : , : , }
创建字典
obj = {'name': '哪吒', '生命': 30}
obj = dict(英雄名字='哪吒', 最大生命=7268)
取值
obj['name']
obj.get('name')
遍历字典
for key in obj:
print(key)
for value in obj.values():
print(value)
增加字典元素
obj['性别'] = '未知'
删除字典元素
obj.pop('name') # 删除指定键值对
obj.popitem() # 删除最后插入的键值对
del obj['name'] # 删除指定键值对
obj.clear() # 清空字典
复制字典
new_obj = obj.copy()
new_obj = dict(obj)
元组
不能修改,有序,可用下标检索
创建元组
tuple = ('',) # 单个元素需要加逗号
合并元组
tuple3 = tuple1 + tuple2
集合
无序,不可重复
创建集合
gather = {1, 2, 3}
访问集合元素
for var in gather:
print(var)
判断元素是否在集合中
1 in gather
增加集合元素
gather.add(4) # 增加单个元素
gather.update([5, 6]) # 增加多个元素
删除集合元素
gather.discard(4) # 删除元素,不存在不会报错
gather.remove(4) # 删除元素,不存在会报错
集合运算
# 并集
gatherA.union(gatherB)
gatherA | gatherB
# 交集
gatherA.intersection(gatherB)
gatherA & gatherB
# 差集
gatherA.difference(gatherB)
gatherA - gatherB
# 对称差集
gatherA.symmetric_difference(gatherB)
gatherA ^ gatherB
函数
4个空格是一个作用域
定义函数
def cal(qty=6, item='bananas', price=5.74):
print(f'{qty} {item} cost ${price:.2f}') # f代表格式化字符串字面值,.2f表示保留两位小数
cal(price=2.29)
返回值函数
def absolute_value(num):
if num >= 0:
return num
else:
return -num
类和对象
创建类
class Bird:
def __init__(self, n, c, s): # self相当于this,所有方法的第一个参数都是self
self.name = n
self.color = c
self.size = s
def get_description(self):
description = f'{self.name} {self.color} {self.size}'
print(description)
# 创建对象
my_bird = Bird('鹦鹉', '绿色', '中等大小')
继承
class Penguin(Bird):
def __init__(self, n, c, s):
super().__init__(n, c, s) # 调用父类的初始化方法
模块
引入模块
import sys
print(sys.path) # sys.path是Python的系统变量,是Python搜索模块的路径列表
引入方法
from 模块名 import 方法名
from module_name import * # 导入模块中的所有对象
from utils import max_num as max_n # 使用别名
异常处理
try-except-else-finally
try:
print(1 / 0)
except ZeroDivisionError:
print("ZeroDivisionError happened")
else:
print("Exception not happened")
finally:
print("Finally is executed!")
主动抛出异常
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
以上就是整理后的Python基础笔记,希望对你有所帮助!如果有任何问题或建议,欢迎在评论区留言。