day05 运算符和流程控制
Day05
-
逻辑运算符
-
成员运算符
-
身份运算符
-
流程控制(重点)
and 与 #可以用and链接多个条件,会按照从左到右的顺序依次判断,有一个为False,则判定结果未False,只有所有条件为True,最终结果才是True 2 > 3 and 1 != 1 and True and 3 > 2 #因为1!=1为False,所以判定结果为false or 或 # 可以用or连接多个条件,会按照从左到右的顺序依次判断,一旦某一个条件为True,则无需再往右判断,可以立即判定最终结果就为True,只有在所有条件的结果都为False的情况下,最终结果才为False 2 > 1 or 1 != 1 or True or 3 > 2 #因为2>1为True,所以最终结果为True not 非(取反) not True
成员运算符
#判定某个个体是否在某个群体中
符号: in(在) not in (不在)
name_list = ['kevin', 'jack', 'tony', 'tom']
print('kevin' in name_list) # True
print('k' in 'kevin') #True
身份运算符
#判断两个值是否相等
符号:is(比较的是内存地址) ==(比较的是值)
s1 = ['a', 'b', 'c']
s2 = ['a', 'b', 'c']
print(s1 == s2) #True
print(id(s1))
print(id(s2))
print(s1 is s2) #False
'''
值相等的内存地址不一定相等
内存地址相等的值一定相等
'''
流程控制
# 控制事物的执行流程
流程控制总共有3种情况:
1. 顺序结构 # 就是自上而下的执行
2. 分支结构 # 分支结构就是根据条件判断的真假去执行不同分支对应的子代码
3. 循环结构 # 循环结构就是重复执行某段代码块
分支结构
if判断
"""
注意事项:
1. 根据条件的成立与否,决定是否执行if代码块
2. 我们通过缩进代码块,来表示代码之间的从属关系
3. 不是所有的代码都拥有子代码块
4. 我们推荐使用缩进4格
5. 同属于一个代码块的子代码块缩进量一定要一样
ps:遇到冒号就要回车换行,缩进
"""
# 1. 单if判断
关键字:if
"""
语法格式:
if 判断条件:
print('小姐姐好')
"""
# 2. 双分支结构
"""
语法格式:
if 判断条件:
条件成立执行的子代码块
else:
条件不成立执行的子代码块
"""
# 3. 多分支结构
"""
语法格式:
if 条件1:
条件1成立执行的子代码块
elif 条件2:
条件1不成立条件2成立执行的子代码块
elif 条件3:
条件1、2不成立条件3成立执行的子代码块
elif 条件4:
条件1、2、3不成立条件4成立执行的子代码块
else:
以上条件都不成立的时候执行的代码块
"""
# else语句是可有可无的
while循环
"""
while语法格式
while 条件:
循环体
"""
while True:
username=input('username:>>>')
password=input('password:>>>')
if username == 'kevin' and password == '123':
print('登录成功')
else:
print('登录失败')
while + break
# count = 0
while True:
username=input('username:>>>')
password=input('password:>>>') #
if username == 'kevin' and password == '123':
print('登录成功')
break # 结束本层循环
else:
print('登录失败')
标志位的使用
flag = True #定义一个标志为True
while flag:
username=input('username:>>>')
password=input('password:>>>') #
if username == 'kevin' and password == '123':
print('欢迎光临')
while flag:
cmd=input('请输入你的指令:>>>')
if cmd == 'q':
# 结束程序
flag = False #当flag = False时,后面的代码块还会继续执行,直到这个判断结束为止
print('正在执行你的指令:%s' % cmd)
else:
print('登录失败')