Python条件测试表达式用法详解
1、Python中的真假
1)、任何非0数字和非空对象都为真;
2)、数字0、空对象和特殊对象None均为假;
3)、比较和相等测试会递归地应用于数据结构中;
4)、返回值为True或False;
2、Python组合条件测试
X and Y: 与运算
X or Y: 或运算
not X: 非运算
3、Python条件测试内置变量及代码块
break: 跳出最内层的循环;
continue: 跳到所处的最近层循环的开始处;
pass: 点位语句
else代码块:循环正常终止才会执行;如果循环终止是由break跳出导致的,则else不会执行;
4、if条件判断语法格式及用法示例:
1).A = X if Y else Z
if Y:
A= X
else:
A= Z
例1:if基础用法示例:
In [1]: l1 = [1,2,3,4]
In [2]: x = 1
In [3]: if x in l1:
....: print "x inl1"
....:
x in l1
2).expression1 if boolean_expression elseexpression2
例2:if-else用法示例:
In [4]: y =2
In [5]: if x > y:
print "The max num is %d" % x
else:
print "The max num is %d" % y
....:
The max num is 2
例3:if-else语句用法示例:
In [6]: A = 6
In [7]: B = 9
In [8]: maxnum = A if A > B else B
In [9]: print maxnum
9
3).if boolean_expression:
...
elifboolean_expression:
...
else:
...
例4:if-elif-else用法示例:
In [10]: name = "Will"
In [11]: if name == "Field":
....: print "Myname is %s." % name
....: elif name == "Kin":
....: print "My name is%s." % name
....: else:
....: print "I amWill!"
....:
I am Will!