运算符、流程控制(if、while)笔记

算术运算符

算术运算符用于数学运算

比较运算符(返回一个bool值)

用于比较数据的大小

运算符 描述 实例
== 比较对象是否相等 (a==b)返回1
!= 比较两个对象是否不相等 (a!=b)返回1
< 比较前者是否小于后者 (a<b)返回1
> 比较后者是否小于前者,是则返回1,否则返回0 (a>b)返回1
<> 比较两个对象是否不相等 (a<>b)返回1与!=类似
>= 比较后者是否小于等于前者 (a>=b)返回1
<= 比较前者是否小于等于后者 (a<=b)返回1

逻辑运算符(把多个条件同时叠加)

and(与) or(或)not(非,条件为True,输出为false)

运算符 逻辑表达方式 描述
and x and y
or x or y
not not x 非,如果x为True则返回False

赋值运算符

身份运算符

运算符 逻辑表达方式 描述
is x is y 每一个变量值都有内存地址(身份), is比较内存地址是否相等,相等则返回True,不相等则返回False
is not x is not y is not 比较内存地址是否不等,不相等返回True,相等则返回False

位运算符

运算符 描述 实例
& 参与运算的两个值二进制位如果都为1则该位结果为1,否则为0 (a&b)
| 只要对应的二进制位有一个为1,结果就为1 (a|b)
^ 对应的两个二进制位相异时结果为1 (a^b)
~ 对数字的每个二进制位取反,1变0,0变1 (~a)
<< 运算数的各二进制位左移若干位 a<<2
>> 运算数的各二进制位右移若干位 a>>2

成员运算符

判断元素是否在容器里面,

运算符 描述 实例
in 如果指定序列中找到值,返回True
not in 如果指序列没有找到返回值,返回True

python运算优先级

先比较再逻辑

括号优先级最高(经验)

流程控制:向一个方向变化

if判断

单分支结构

if 条件:(:表示接下来的代码需要缩进)

双分支结构

if 条件:

else:

多分支结构

if 条件1:

elif 条件2:

elif 条件3:

else :

pass 啥也不做 占个位置

award = 0
profit = float(input('Please input the total profit(单位:万):'))
if profit <= 10:
    award = profit*0.1
elif profit > 10 and profit <= 20:
    award = (profit-10)*0.075+1
elif profit > 20 and profit <= 40:
    award = (profit-20)*0.05+1+0.75
elif profit >40:
    award = (profit-40)*0.03+1+0.75+1
print(award)

while循环

while 条件:
code1
code2
code3
...

while + break

break用于跳出本层循环

while count <3:
    in_age = int(input('please input the age :'))
    if in_age == age:
        print('you are right')
        break

while + continue

continue用于跳出本次循环

while 1:
     if count ==100 :
         break
     count += 2
     if count in [22,46,68,98] :
        continue
     i = i + count
 print(i)

tag 控制循环退出

tag = true
while tag:
    user_db = 'xiaozhang'
    pwd_db = '123'
    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        while tag:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                tag = False
            print(f'{cmd} 功能执行')
    else:
        print('username or password error')

print('退出了while循环')
posted @ 2019-09-11 18:50  ylpb  阅读(187)  评论(0编辑  收藏  举报