一、流程控制语句
1 if… else…
例:判断a是否为空
a = 'a'
if a :
print('ok')
else :
print('不ok')
输出:
ok
2 while
while 条件:
#循环体
#如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件
#如果条件为假,那么循环体不执行,循环终止
例:打印0到10之间的偶数
a = 0
while a < 10:
a += 2
print(a)
输出:
2
4
6
8
10
a. while True代表死循环,就是条件一直为真,循环体会一直执行下去
b.while … else …循环完毕执行else下的代码
a = 0
while a < 10:
a += 2
print(a)
else:
print('循环正常执行完啦')
输出:
2
4
6
8
10
循环正常执行完啦
c.break跳出循环
a = 0
while True:
if a >4:
break
print(a)
a += 1
输出:
0
1
2
3
4
d.continue跳出本次循环
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
输出:
1
2
4
5
3 for 循环
迭代式循环for ,语法如下:
for i in range(10):
#缩进的代码
range为内置函数
例:
for i in range(5,11,2): #顾头不顾尾
print(i)
输出:
5
7
9
for循环可以遍历字符串、列表、元组、集合、字典
例:
res = 'Hello,World'
for i in res:
print(i)
输出:
H
e
l
l
o
,
W
o
r
l
d
注意:int 和 float 不可以for遍历,for遍历字典的是key
二、内置函数
1 len计算长度
a = 'hello,world'
res = len(a)
print(res)
输出:
11
l1 = [1,2,3,4]
print(len(l1))
输出:
4
2 in 在…里面 , not in 不在…里面
info = {
'name':'aaa',
'age': '12'
}
print('12' not in info.values())
输出:
False