🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
--: 作者:不知百度知 2022年9月 [TOC] ## 1. if三元表达式(三元运算符) ### 1.1 说明 使用一行代码快速判断,更换复杂的多行if语句,使代码能够简单地维护。 ### 1.2 其它语言的三元表达式 > 判段的条件 ? 条件为真时的结果:条件为假时的结果 ```java public class java { public static void main(String[] args){ int x = 100; int y = 101; int MAX = (x > y)? x: y; System.out.println("MAX:" + MAX); } } ``` ### 1.2 python的三元表达式 > 条件为真时的结果 if 判段的条件 else 条件为假时的结果 ```python x = 4 y = 99 if x > 3 else 999 ``` ## 2. 变量的真假 在 Python 看来,只有变量的值为0或空、长度为0时,才会被看作假(注意引号、括号里边啥都没有,连空格都不要有!): ` False None 0 "" '' () [] {} ` 其他一切都被解释为真! 测试示例: ``` if 0: print('True1') else: print('False1') if "": print('True2') else: print('False2') if []: print('True3') else: print('False3') if {}: print('True4') else: print('False4') if (): print('True5') else: print('False5') ``` 结果为 ``` False1 False2 False3 False4 False5 ``` 所以我们经常会见到别人的代码这样判断 ``` if 变量: xxx ``` 比如: ``` a = 10 if a: # a大于0,条件为真 a -= 1 else: a = 10 ``` ## 3. 短路逻辑(short-circuit logic) 逻辑操作符有个有趣的特性:在不需要求值的时候不进行操作。 <div style='height:20px'></div> 这么说可能比较“高深”,举个例子,表达式 x and y ,需要 x 和 y 两个变量同时为真 (True) 的时候,结果才为真。 <div style='height:20px'></div> 因此,如果当 x 变量得知是假 (False) 的时候,表达式就会立刻返回 False ,而不用去管 y 变量的值。 这种行为被称为短路逻辑( short-circuit logic )或者惰性求值( lazy evaluation )。 <div style='height:20px'></div> 这种行为同样也应用于 or 操作符,Python 的做法是如果 x 为假,表达式会返回 x 的值 (0) ,否则它就会返回 y 的值。 ``` a = 3 and 4 # 结果为4 b = 3 or 4 # 结果为3 ``` ## 4. 对象的类型判断 - type(对象) == 类型 - isinstance(对象, 类型) python中type可以获得一个对象的数据类型,isinstance可以判断一个对象的数据类型,他们的区别有两点: ### 4.1. isinstance更加灵活 type只是返回一个对象的数据类型,而isinstance可以判断这个对象的数据类型是否为某几个数据类型中的一个。 假设我们要判断一个对象的数据类型是否为int或者float,两个函数的写法示例如下 ~~~python a = 4 # 使用type if type(a) == int or type(a) == float: print('yes') # 使用isinstance if isinstance(a, (int, float)): print('yes') ~~~ 显然,在这种场景下,isinstance更有优势 ### 4.2. 判断存在继承关系的情况 ~~~python class A: pass class B(A): pass a = A() b = B() print(type(b) == A) # False print(isinstance(b, A)) # True ~~~ B是A的子类, type(b)返回的是类B, 不等于A, 但B是A的子类,因此,我们可以认为b也是A的对象,面对这种存在继承关系的情况,应当使用isinstance。 官方推荐用第二种方法判断变量的类型,现在先有个初步印象,学到后面再作详细解释。 ## 5. 运算符优先级 以下表格列出了从最高到最低优先级的所有运算符: | 运算符 | 描述 | | --- | --- | | \*\* | 指数 (最高优先级) | | ~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) | | \* / % // | 乘,除,取模和取整除 | | \+ - | 加法减法 | | \>> << | 右移,左移运算符 | | & | 位 'AND' | | ^ | | 位运算符 | | >= | 比较运算符 | | <> == != | 等于运算符 | | \= %= /= //= -= += \*= \*\*= | 赋值运算符 | | is is not | 身份运算符 | | in not in | 成员运算符 | | not and or | 逻辑运算符 | 常见几种类型运算符优先级示意图 ![](https://img.kancloud.cn/8c/b2/8cb2f457186af753c267f3a3dea2d696_845x490.png) > 练习 - 请用最快速度说出答案: not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9 <div style='height:100px'></div> not or and 的优先级是不同的: not > and > or,我们按照优先级给它们加上括号: ``` (not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9) == 0 or 0 or 4 or 6 or 9 == 4 ``` 【Tip】 温馨提示:为了更好的表达你的程序,有些括号还是不能省下的,毕竟不是所有程序员都跟你一样都将优先级烂透于心的。