python容易忘记的知识点

位运算符

操作符名称示例
~按位取反~4
&按位与4 & 5
|按位或4 | 5
^按位异或4 ^ 5
<<左移4 << 2
>>右移4 >> 2
print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

is,is not运算符

操作符名称示例
in存在'A' in ['A', 'B', 'C']
not in不存在'h' not in ['A', 'B', 'C']
is"hello" is "hello"
is not不是"hello" is not "hello"
a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

注意:

  • is, is not 对比的是两个变量的内存地址
  • ==, != 对比的是两个变量的值
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
  • 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。

运算符的优先级

运算符描述
**指数(最高优先级)
按位翻转,一元加号和减号
* / % //乘,除,取模和取整除)
+ -加法减法
>> <<右移,左移运算符
&位‘AND’
^|位运算符
<=<>>=比较运算符
<>==!=等于运算符
=%=/=//=-=+=*=**=赋值运算符
is is not身份运算符
in not in成员运算符
not and or逻辑运算符
print(-3 ** 2)  # -9
print(3 ** -2)  # 0.1111111111111111
print(1 << 3 + 2 & 7)  # 0
print(-3 * 2 + 5 / -2 - 4)  # -12.5
print(3 < 4 and 4 < 5)  # True

数据类型与转换

类型名称示例
int整型 <class 'int'>-876, 10
float浮点型<class 'float'>3.149, 11.11
bool布尔型<class 'bool'>True, False
#获取类型信息 type(object)
a = 1031
print(a, type(a)) # 1031 <class 'int'>
print(1., type(1.)) # 1.0 <class 'float'>

#Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)
b = dir(int)
print(b)

#想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现
import decimal
from decimal import Decimal
#Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]),Decimal默认精度28位
a = decimal.getcontext()
print(a)
#使 1/3 保留 4 位,用 getcontext().prec 来调整精度。
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c) #0.3333

布尔型

布尔 (boolean) 型变量只能取两个值,True 和 False。当把布尔型变量用在数字运算中,用 1 和 0 代表 True 和 False。


print(True + True)  # 2
print(True + False)  # 1
print(True * False)  # 0

确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True

  • 对于数值变量,0, 0.0 都可认为是空的。
  • 对于容器变量,里面没元素就是空的。
#都是False
print(bool(0),bool(0.00),bool(()),bool({}),bool([]),bool(set()))

isinstance

如果要判断两个类型是否相同推荐使用 isinstance().会认为子类是一种父类类型,考虑继承关系。

print(isinstance(1, int))  # True
print(isinstance(5.2, float))  # True
print(isinstance(True, bool))  # True
print(isinstance('5.2', str))  # True

类型转换

  • 转换为整型 int(x, base=10)
  • 转换为字符串 str(object='')
  • 转换为浮点型 float(x)
print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10 + 10))  # 20
print(str(10.1 + 5.2))  # 15.3

while - else 循环

while 布尔表达式:
    代码块
else:
    代码块

while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。

for - else 循环

for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

for循环正常执行完的情况下,执行else输出,如果for循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容,与while - else语句一样。

推导式

列表推导式

[ expr for value in collection [if condition] ]
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)

# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

元组推导式

( expr for value in collection [if condition] )
a = (x for x in range(10))
print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

字典推导式

{ key_expr: value_expr for value in collection [if condition] }
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}

集合推导式

{ expr for value in collection [if condition] }
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}

异常处理

异常就是运行期检测到的错误。计算机语言针对可能出现的错误定义了异常类型,某种错误引发对应的异常时,异常处理程序将被启动,从而恢复程序的正常运行。

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转换错误导致的异常

try - except - else 语句

如果在try子句执行时没有发生异常,Python将执行else语句后的语句。

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码

使用except而不带任何异常类型,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。

try:
    检测范围
except(Exception1[, Exception2[,...ExceptionN]]]):
   发生以上多个异常中的一个,执行这块代码
else:
    如果没有异常执行这块代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值