if分支语句:
if···语句:
score = 80
if score >= 60:
print('成绩及格')
if···else···语句:
score = 80
if score >= 60:
print('成绩及格')
else:
print('成绩不及格')
if···elif···语句:
score = 80
if score >= 90:
print('成绩优秀')
elif score >= 60:
print('成绩及格')
else:
print('成绩不及格')
for循环语句:
for···in···语句:
lst = [0, 1, 2, 3, 4]
for item in lst:
print(item, end=',')
# 0,1,2,3,4,
for···in··· + range():
for item in range(0, 5):
print(item, end=',')
# 0,1,2,3,4,
for···in··· + else···:
在for循环结束后,执行else语句
lst = [0, 1, 2, 3, 4]
for item in lst:
print(item, end=',')
else:
print('循环结束')
# 0,1,2,3,4,循环结束
break:终止整个循环:
break会提前终止循环,终止之后的循环不被执行,包括else语句。
for item in range(0, 10):
if item == 5:
break
print(item, end=',')
else:
print('循环结束')
# 0,1,2,3,4,
continue:中止本次循环,继续执行下次循环:
continue只会中断某次循环,不影响for循环完整运行,会执行else。
for item in range(0, 10):
if item % 2 == 0:
continue
print(item, end=',')
else:
print('循环结束')
# 1,3,5,7,9,循环结束
pass:占位作用,什么都不执行:
pass没有实际作用,不影响for循环正常运行,会执行else。
for item in range(0, 10):
if item % 2 == 0:
pass
else:
print(item, end=',')
else:
print('循环结束')
# 1,3,5,7,9,循环结束
while循环语句:
while语句:
item = 0
while item < 10:
print(item, end=',')
item += 1
# 0,1,2,3,4,5,6,7,8,9,
while + else:
item = 0
while item < 10:
print(item, end=',')
item += 1
else:
print('循环结束')
# 0,1,2,3,4,5,6,7,8,9,循环结束
break、continue、pass 用法与for循环一致
附1, print函数:
默认print函数会自动换行,等同于print(***, end='\n');在print函数中加入"end"关键字,可以在输出结果后面拼接指定字符串:
lst = [1, 2, 3, 4, 5]
for item in lst:
print(item, end='') # 12345
for item in lst:
print(item, end=',') # 1,2,3,4,5,
for item in lst:
print(item, end='\n') # 换行输入1~5, 等同于print(item)
附2, range函数:
range(起始, 结束, 步长),起始、结束、步长都是int类型,生成一个int序列,包含起始不包含结束,序列每个元素间隔为步长(省略步长默认为1)
for item in range(0, 5):
print(item, end=',')
# 0,1,2,3,4,
for item in range(0, 10, 2):
print(item, end=',')
# 0,2,4,6,8
|