Python学习进程(4)运算符
本节主要介绍Python的运算符。
(1)Python语言支持的运算符类型:
1.算术运算符 2.比较(关系)运算符 3.赋值运算符 4.逻辑运算符 5.位运算符 6.成员运算符 7.身份运算符 8.运算符优先级
(2)详细介绍Python的运算符:
1)算术运算符:
>>> a=20 >>> b=5 >>> c=a+b;print(c) 25 >>> c=a-b;print(c) 15 >>> c=a*b;print(c) 100 >>> c=a/b;print(c) 4.0 >>> c=a%b;print(c) 0 >>> c=a**b;print(c) #乘方运算符 3200000 >>> c=a//b;print(c) #取商运算 4
2)比较运算符:
>>> a=10;b=20; >>> print(a==b) False >>> print(a!=b) True >>> print(a>b) False >>> print(a<b) True >>> print(a>=b) False >>> print(a<=b) True >>> print(a>b|a<b) #在c语言中是a>b||a<b,而在这里不是 False >>> print(5 in [1,3,5]) True
3)赋值运算符:
>>> a=10;c=5; >>> c+=a;print(c); 15 >>> c-=a;print(c); 5 >>> c*=a;print(c); 50 >>> c/=a;print(c); 5.0 >>> c**=a;print(c); 9765625.0 >>> c//=a;print(c); 976562.0 >>> c%=a; print(c); 2.0
4)位运算符:
>>> a=45;b=21; >>> print(a&b); //二进制的与运算 5 >>> print(a|b); //二进制的或运算 61 >>> print(a^b); //二进制的异或运算 56 >>> print(~a,~b); //二进制的取反运算 -46 -22 >>> print(a>>2,b>>2); //左移位运算 11 5 >>> print(a<<2,b<<2); //右移位运算 180 84
5)逻辑运算:
>>> a=True;b=False; >>> print(a and b) //布尔型变量的运算是布尔型 False >>> print(a & b) False >>> a=True;b=False; >>> print(a and b,a & b); False False >>> print(a or b,a | b); True True >>> print(not a,not b); False True >>> a=1;b=0; >>> print(a and b); //整型变量的运算是整型 0 >>> print(a or b); 1 >>> print(not a,not b); //not运算返回布尔型 False True
6)成员运算符:(测试字符串、元组或列表)
>>> a=5;list=[1,3,5,7]; >>> print(a in list); True >>> print(a not in list); False >>> tempStr='你好啊,小家伙'; >>> print('好' not in tempStr); False
7)身份运算符:(身份运算符用于比较两个对象的存储单元)
>>> a=20;b=20 >>> print(a is b); True >>> c=25; >>> print(a is not c); True
(3)运算符的优先级: