Python01 学习记录
因为过去学过Python,所以这里只做整理总结。。
一. 运算符
优先级 | 运算符 | 描述 |
---|---|---|
1 | lambda | Lambda表达式 |
2 | or | 布尔“或” |
3 | and | 布尔“与” |
4 | notx | 布尔“非” |
5 | in,not in | 成员测试 |
6 | is,is not | 同一性测试 |
7 | <,<=,>,>=,!=,== | 比较 |
8 | | | 按位或 |
9 | ^ | 按位异或 |
10 | & | 按位与 |
11 | <<,>> | 移位 |
12 | +,- | 加法与减法 |
13 | *,/,% | 乘法、除法与取余 |
14 | +x,-x | 正负号 |
15 | ~x | 按位翻转 |
16 | ** | 指数 |
17 | x.attribute | 属性参考 |
18 | x[index] | 下标 |
19 | x[index:index] | 寻址段 |
20 | f(arguments…) | 函数调用 |
21 | (experession,…) | 绑定或元组显示 |
22 | [expression,…] | 列表显示 |
23 | {key:datum,…} | 字典显示 |
24 | ‘expression,…’ | 字符串转换 |
二.数字类型
类型 | 名称 | 范围 |
---|---|---|
int | 整型 | -231~231-1(32bit) -263~263-1(64bit) | |
long | 长整型 | 受机器内存限制,可表示 |
float | 浮点型 | 类似与c中double,64bit |
complex | 复数 (x+yj) | |
bool | 布尔类型 | True、False |
#判断类型
type(object)
#判断两个类型是否相同
isinstance(oj1,oj2)
三.数据类型
- 字符串String
- 列表List
- 元祖Tuple
- 字典dictionary
四. print()函数
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
'''
·将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
·关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
·关键字参数end是输出结束时的字符,默认是换行符\n;
·关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
·关键字参数flush是立即把内容输出到流文件,不作缓存。
'''
五、条件函数
- if 语句
- if-else语句
- if-elif-else语句
- assert关键词
assert 关键词 (关键词为False时会报AssertionError异常)
六、循环语句
- while
- while-else
- for
- for-else
- enumerate()函数
enumerate(sequence, [start=0])
'''
sequence:一个序列、迭代器或其他支持迭代对象。
start:下标起始位置。
返回 enumerate(枚举) 对象
'''
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1)) # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
- 推导式
#列表推导式
[ expr for value in collection [if condition] ]
x = [i ** 2 for i in range(1, 10)]
#元组推导式
( expr for value in collection [if condition] )
a = (x for x in range(10))
#字典推导式
{ key_expr: value_expr for value in collection [if condition] }
#集合推导式
{ expr for value in collection [if condition] }
异常处理
1. Python 标准异常总结
-
BaseException:所有异常的 基类 Exception:常规异常的 基类
-
StandardError:所有的内建标准异常的基类
-
ArithmeticError:所有数值计算异常的基类
-
FloatingPointError:浮点计算异常
-
OverflowError:数值运算超出最大限制
-
ZeroDivisionError:除数为零
-
AssertionError:断言语句(assert)失败
-
AttributeError:尝试访问未知的对象属性
-
EOFError:没有内建输入,到达EOF标记
-
EnvironmentError:操作系统异常的基类 IOError:输入/输出操作失败
-
OSError:操作系统产生的异常(例如打开一个不存在的文件)
-
WindowsError:系统调用失败
-
ImportError:导入模块失败的时候
-
KeyboardInterrupt:用户中断执行
-
LookupError:无效数据查询的基类
-
IndexError:索引超出序列的范围
-
KeyError:字典中查找一个不存在的关键字
-
MemoryError:内存溢出(可通过删除对象释放内存)
-
NameError:尝试访问一个不存在的变量
-
UnboundLocalError:访问未初始化的本地变量
-
ReferenceError:弱引用试图访问已经垃圾回收了的对象
-
RuntimeError:一般的运行时异常
-
NotImplementedError:尚未实现的方法
-
SyntaxError:语法错误导致的异常
-
IndentationError:缩进错误导致的异常
-
TabError:Tab和空格混用
-
SystemError:一般的解释器系统异常
-
TypeError:不同类型间的无效操作
-
ValueError:传入无效的参数
-
UnicodeError:Unicode相关的异常
-
UnicodeDecodeError:Unicode解码时的异常
-
UnicodeEncodeError:Unicode编码错误导致的异常
-
UnicodeTranslateError:Unicode转换错误导致的异常
2. Python标准警告总结
- Warning:警告的基类
- DeprecationWarning:关于被弃用的特征的警告
- FutureWarning:关于构造将来语义会有改变的警告
- UserWarning:用户代码生成的警告
- PendingDeprecationWarning:关于特性将会被废弃的警告
- RuntimeWarning:可疑的运行时行为(runtime behavior)的警告
- SyntaxWarning:可疑语法的警告
- ImportWarning:用于在导入模块过程中触发的警告
- UnicodeWarning:与Unicode相关的警告
- BytesWarning:与字节或字节码相关的警告
- ResourceWarning:与资源使用相关的警告
3. try - except 语句
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
try 语句按照如下方式工作:
首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。
如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。
最后执行try - except语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
举个🌰
try:
int("abc")
s = 1 + '1'
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
print('类型出错\n原因是:' + str(error))
except ValueError as error:
print('数值出错\n原因是:' + str(error))
# 数值出错
# 原因是:invalid literal for int() with base 10: 'abc'
4. try - except - finally 语句
try: 检测范围
except Exception[as reason]: 出现异常后的处理代码
finally: 无论如何都会被执行的代码
不管try子句里面有没有发生异常,finally子句都会执行
def divide(x, y):
try:
result = x / y
print("result is", result)
except ZeroDivisionError:
print("division by zero!")
finally:
print("executing finally clause")
5. try - except - else 语句
#如果在try子句执行时没有发生异常,Python将执行else语句后的语句。
try:
检测范围
except:
出现异常后的处理代码
else:
如果没有异常执行这块代码
6. raise语句
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!