1. python 运算符
要点
算术运算符 + - * / %(取模,返回除法的余数) **(求幂,返回x的y次幂) //(取整除,返回商的整数部分)
比较(关系)运算符 == != <> >< >= <=
赋值运算符 = += -= = /= %= *= //=
逻辑运算符 and和 or或 not非
and和 真真为真,其他为假
or或 假假为假,其他未真
not非 取反
位运算符 & | ^ - << >>
&按位与运算符:参与运算的两个值,如果连个相应都未1,则该位的结果为1,否则为0
|按位或运算符:只要对应的二个二进制有一个为1,结果位就为1
^按位异或运算符,两个二进制不同为1
-按位取反运算符,对数据的每个二进制位取反,即把1变为0,把0变为1,在一个有符号二进制数的补码形式
<< 左移
>> 右移
成员运算符
in指定的序列中找到值返回True,否则返回False。
not in指定的序列中没有找到值返回True,否则返回False
身份运算符
is 是否一样,判断两个标识符是不是引用自一个对象
is not 是否不一样,判断两个标识符是不是引用自不同对象
运算符优先级
第一等级**
第二等级*/ // %
第三等级+-
第四等级>><<
第五等级&
第六等级^|
第七等级<= => ><
第八等级 == !=
第九等级 = += -= *= /= **=
第十等级 is is not
第十一等级 in not in
第十二等级 not or and
1.1算术运算符
a=10
b=4
c=0
c=a+b
c=a%b
c=a**b
c=a//b
print c
1.2 比较(关系)运算符
if (a==b):
print 'yes'
else:
print 'no'
if (a!=b):
print 'yes'
else:
print 'no'
if (a>=b):
print 'yes'
else:
print 'no'
if (a<=b):
print 'yes'
else:
print 'no'
1.3赋值运算符
a = 10
b = 4
c = 12
c += a
c += b
c -= a
c -= b
c *= a
c /= b
c %= b
c **=a
c //= b
print c
1.4 逻辑运算符
a = True
b = False
c = 12
if (a and b):
print 'yes'
else:
print 'no'
if (a or b):
print 'yes'
else:
print 'no'
if not(a and b): #取反
print 'yes'
else:
print 'no'
1.5 位运算符 ,二进制运算
a = 10
b = 9
c = 0
#c = a & b
#c = a | b
#c = a^b
#c = -a
c = a<<2
c = a>>2
print c
1.6 成员运算符
list = [1,2,3,4,5,6,7]
if (a in list):
print 'yes'
else:
print 'no'
if (a not in list):
print 'yes'
else:
print 'no'
1.7身份运算符
a = 10
b = 9
c = 0
if (a is b):
print 'yes i is'
else:
print 'no not'
if (a is not b):
print 'yes i is'
else:
print 'no not'
d = (1+2)*3/2
print d
2.if 判断
用户登录案例
##创建一个用户名
#coding=utf-8
username = 'admin'
password = 'xulaoshi123456'
user_input = raw_input('请输入你的用户名:')
pass_input = raw_input('请输入密码:')
if username == user_input and password == pass_input:
print '欢迎登录 %s'%user_input #%s是字符串变量,user_input变量
else:
print'登录失败,%s用户名或密码错误'%user_input
##新增访客用户
username = 'admin'
password = 'xulaoshi123456'
user_input = raw_input('请输入你的用户名:')
pass_input = raw_input('请输入密码:')
if username == user_input and password == pass_input:
print '欢迎登录 %s'%user_input #%s是字符串变量,user_input变量
elif user_input == 'guest':
print'登录成功,但是你只有只读权限'
else:
print'登录失败,%s用户名或密码错误'%user_input