1、Python比较运算符(关系运算符)
#== 用来比较两个变量的值是否相等,而 is 则用来比对两个变量引用的是否是同一个对象
实例:
import time
t1= time.gmtime()#gmtime获取当前最新时间
t2= time.gmtime()
print(t1 == t2)
print(t1 is t2)
2、Python逻辑运算符及其用法
#a and b 当 a 和 b 两个表达式都为真时,a and b 的结果才为真,否则为假
#a or b 当 a 和 b 两个表达式都为假时,a or b 的结果才是假,否则为真。
# not a 如果 a 为真,那么 not a 的结果为假;如果 a 为假,那么 not a 的结果为真。相当于对 a 取反。
实例
age = int(input('请输入年齡:'))
height = int(input('请输入身高:'))
if age>=18 and age<=30 and heigeht>=175 and height<=185:
print('恭喜,你符合报考飞行员的条件')
else:
print('抱歉,你不符合报考飞行员的条件')
#对于 and 运算符,两边的值都为真时最终结果才为真,但是只要其中有一个值为假,那么最终结果就是假,所以 Python 按照下面的#规则执行 and 运算:
如果左边表达式的值为假,那么就不用计算右边表达式的值了,因为不管右边表达式的值是什么,都不会影响最终结果,最终结果都是假,此时 and 会把左边表达式的值作为最终结果。
如果左边表达式的值为真,那么最终值是不能确定的,and 会继续计算右边表达式的值,并将右边表达式的值作为最终结果。
print("" and "http://c.biancheng.net/python/")
print("1" and "http://c.biancheng.net/python/")
#对于 or 运算符,情况是类似的,两边的值都为假时最终结果才为假,只要其中有一个值为真,那么最终结果就是真,所以 Python 按照下面的规则执行 or 运算:
如果左边表达式的值为真,那么就不用计算右边表达式的值了,因为不管右边表达式的值是什么,都不会影响最终结果,最终结果都是真,此时 or 会把左边表达式的值作为最终结果。
如果左边表达式的值为假,那么最终值是不能确定的,or 会继续计算右边表达式的值,并将右边表达式的值作为最终结果。
print("" or "http://c.biancheng.net/python/")
print("1" or "http://c.biancheng.net/python/")
实例:
url = "http://c.biancheng.net/cplus/"
print("----False and xxx-----")
print( False and print(url) )
print("----True and xxx-----")
print( True and print(url) )
print("----False or xxx-----")
print( False or print(url) )
print("----True or xxx-----")
print( True or print(url) )
3、Python三目运算符(三元运算符)
a = 1
b = 2
if a>b:
max=a
else:
max=b
print(max)
aa = a if a>b else b
print(aa)
#使用 if else 实现三目运算符(条件运算符)的格式如下:
#exp1 if contion else exp2
#condition 是判断条件,exp1 和 exp2 是两个表达式。如果 condition 成立(结果为真),就执行 exp1,并把 exp1 #的结果作为整个表达式的结果;如果 condition 不成立(结果为假),就执行 exp2,并把 exp2 的结果作为整个表达式的结果。
实例:
a=0.5
b=2
c=0.3
d=1
aa = a if a>b else ( c if c>d else d )
print(aa)
a = int(input('a:'))
b = int(input('b:'))
print('a>b') if a>b else (print('a<b') if a<b else print('a=b'))
3、Python运算符优先级和结合性一览表
a=8 >> 4
print(a)
print((4+4) <<3)
print(4+(4 <<3))
#<<n,相当于乘以2的n次方,
#>>n,相当于除以2的n次方
#2>>2, 打印出来 为0