#-*- coding: utf-8 -*- """"" #1 Boolean Operations逻辑运算符 #Bool 'and' 与操作,先判断a若不为0,则继续看b,若b也不为0,输出b值.若a为0,则不需要再看b了,直接输出0 # a and b: #(1)如果 a,b都为真,则返回值b. #(2)如果a为假,则返回a. #(3)如果a为真,b为假,返回 #总结: a,b只要有一个为false, a and b 返回fale,否则返回b值 a=0 b=10 print((a and b)) #=0 if( a and b ): print("both a and b are true") #2 Bool 'or'或操作: 先看a,若a为真(不为0)则直接输出a,不需要再看b. 若a为0,则继续看b,若b不为0,输出b值.否则输出0(flase) # a,b a=0 b=10 print((a or b)) #3 Bool 'not' 非操作: a=1 if(not a): print("a value is 0") #若a=0执行这里 else: print("a value is not 0 ") #comparisons比较类型 a=1 b=10 c=0 if(a>b): print("a 大于 b") elif(a>=b): print("a 大于等于 b") elif(a<b): print("a 小于 b") elif(a<=b): print("a 小于等于 b") elif(a==b): print("a 等于 b") elif(a != b): print("a 等于 b") else: print("error comparison") #身份运算符: is /is not #如果变量a与b同为一个类型且值相等,他们的内存地址是同一个即id()是相同的. #如果不同类型或值不相同,两个是不同内存地址的. a=10 b=10 print(id(a),id(b)) if(a is b): print("a and b has the same id") else: print("a and b has not the same id ") if(a is not b): print("a and b has not the same id ") else: print("a and b has the same id") #算术运算符 a=2 b=10 c=9 d=-9 print(a+b) #jia print(a-b) #jian print(a*b) #cheng print(a/b) #chu print(a%b) #取余 print(a**b) #取幂2^10=1024 print(c//a) #取整除 - 向下取接近商的整数。c=9,a=2不能整除,c向下取8才能整除,结果=4 print(d//a) #c=-9,a=2不能整除,d向下取-10才能整除,结果=-5 #赋值运算符 # '=','+=','-=','*=','/=','%=','//=','**=',':=' # ':=':海象运算符 a=10 if(a > 1): print('a>1') if( b:=10 >1): #使用海象运算符省掉一个赋值,使代码更简洁 print('b>1') #位运算符 #‘&’,‘|’,'^','~','>>','<<' #左移/右移方向为箭头方向,变量在符号的在边,符号的右边为移动的位数. a<<2:变量a向左移动2位,a>>2:变量a向右移动2位 a=2 b=10 print(a&b,a|b,a^b,~a,a>>2,a<<2) """ #成员运算符 in/not in a=8 alist=[1,2,3] if a in alist: print('a is in alist') else: print('a is not in list')
python之运算符
最新推荐文章于 2023-04-16 21:50:04 发布
本文详细介绍了Python中的逻辑运算符(and、or、not)及其用法,包括短路逻辑。同时,讲解了比较类型的操作,如大于、小于、等于等,并演示了身份运算符is和is not的使用。此外,还涵盖了算术、赋值、位运算符的实例。最后,提到了成员运算符in和not in的应用。
摘要由CSDN通过智能技术生成