if判断
常规用法
语法记忆方法
if+空格+条件+冒号
tab缩进代码体
tab缩进代码体
tab缩进代码体
三目运算
满足条件的结果 if 条件 else 不满足条件的结果
多分枝
if 条件1:
code1
elif 条件2:
code1
elif 条件3:
code1
else:
code1
逻辑运算符
原理
(1) not的优先级最高,就是把紧跟其后的那个条件结果取反,所以not与紧跟其后的条件不可分割
(2) 如果语句中全部是用and连接,或者全部用or连接,那么按照从左到右的顺序依次计算即可
(3) 如果语句中既有and也有or,那么先用括号把and的左右两个条件给括起来,然后再进行运算
and 与(优先级3)
连接左右两个条件,只有在两个条件同时成立的情况下最终结果才为True
or 或(优先级2)
连接左右两个条件,但凡有一个条件成立最终结果就为True
not 非(优先级1)
取反 为true
for循环
for 变量名 in 要循环的数据:
for循环遍历字典
namess = {'name1':'dahai','name2':'xialuo','name3':'xishi'}
默认遍历key值
for i in namess:
print(i)
第二种遍历key值
for i in namess.keys():
print(i)
遍历value值
for i in namess:
print(namess[i])
print(i)
直接取遍历value值
for i in namess.values():
print(i)
遍历键值对
for i in namess.items():
#取key
print(i[0])
#取value
print(i[1])
for循环遍历列表
for a in names:
print(a)
range(0起始,10终止,2步长)
它是一个迭代器range和list等价,但是range的内存占用更小。
列表去重
list1=['aaa','bbb','ccc']
list2 = ['ccc']
for i in list1:
if i in list2:
print('已经有了')
else:
list2.append(i)
枚举 enumerate
goods_list=[
['coffee',30],
['chicken',20],
['iphone',10000],
['car',100000],
['building',200000]
]
for i,item in enumerate(goods_list):
print(i,item)
while循环
while 条件:
while 条件:
code1
code2
code3
while True:
while True:
print('111')
print('222')
**continue 跳过了本次循环**
**break 代表结束本层循环**