View on GitHub

personal-study-nodes

个人学习过程中整理的一些笔记

四、条件语句和循环语句

1. 条件语句

非零数值、非空字符串、非空 list 等,判断为 True,否则为 False

# if语句
score = 90
if 60 < score < 80:
    print('及格')
elif score > 80:
    print('优秀')
else:
    print('不及格')

2. 循环语句

循环控制语句 描述
break 在语句块执行过程中终止循环,并且跳出整个循环
continue 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环
pass pass 是空语句,是为了保持程序结构的完整性
# for 循环
arr = [121, 333, 555, 765]
for item in arr:
    print(item)
# 配合range()函数使用
for item in range(4):   # range(x,y)生成一个从x到y的整数序列,range(4)相当等于range(0,4)
    print(item)
# while 循环
count = 0
while count<5:
    print(count)
    count = count +1

for 和 while 循环的区别:

  • for 循环主要用在迭代可迭代对象的情况。
  • while 循环主要用在需要满足一定条件为真,反复执行的情况。 (死循环+break 退出等情况。)
  • 部分情况下,for 循环和 while 循环可以互换使用(嵌套循环)。