Ⅵ:流程控制

循环结构

什么是循环结构

  • 循环结构就是重复执行某段代码块

为什么要用循环结构

  • 让计算机能够具备人重复执行某件事情的能力

如何使用循环结构?

1.while循环语法

while 条件:
    代码1
    代码2
    代码3

'''
while的运行步骤:
步骤1:如果条件为真,则自上而下的执行代码1、2、3...
步骤2:执行完最后一条代码时再次判断条件,如果条件为Treu则重复步骤1,如果条件为False,则结束循环
'''

while循环以应用案例

案例1:while循环的基本使用:
# 用户认证程序
# 为了避免代码的重复,所以引入while循环
案例2:while+break的使用:
#注意:break用来结束本层循环,break后面的代码都不会执行
# break结束本层循环
username = "jason"
password = "123"
# 记录错误验证的次数
count = 0
while count < 3:
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        break # 用于结束本层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1
案例3:while循环嵌套+break
# 如果while循环嵌套了很多层,要想退出每一层循环则需要在每一层循环都有一个break
username = "jason"
password = "123"
count = 0
while count < 3:  # 第一层循环
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while True:  # 第二层循环
            cmd = input('>>: ')
            if cmd == 'quit':
                break  # 用于结束本层循环,即第二层循环
            print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1
案例4:while循环嵌套+tag的使用
'''
让所有while循环的条件都用同一个变量,该变量的初始值为True,
一旦在某一层将该变量的值改成False,则所有层的循环都结束
'''
username = "jason"
password = "123"
count = 0

tag = True
while tag: 
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while tag:  
            cmd = input('>>: ')
            if cmd == 'quit':
                tag = False  # tag变为False, 所有while循环的条件都变为False 
                break
            print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1
案例5:while+continue的使用
continue用来跳出当前次循环(即跳过本次循环直接进入下一次循环)
注意:在continue之后添加同级代码毫无意义,因为永远无法运行
# 打印1到10之间,除7以外的所有数字
number=11
while number>1:
    number -= 1
    if number==7:
        continue 
    print(number)
案例6:while+else的使用
注意:如果while循环被break终止了,则不会运行else里的代码
# 无break
count = 0
while count <= 5 :
    count += 1
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦   #没有被break打断,所以执行了该行代码
-----out of while loop ------

# 有break
count = 0
while count <= 5 :
    count += 1
    if count == 3:
        break
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
-----out of while loop ------ #由于循环被break打断了,所以不执行else后的输出语句

while循环练习

练习1:寻找1到100之间数字7最大的倍数(结果是98)
number = 100
while number >= 1:
    if number % 7 == 0:
        print(number)
        break
    number -= 1
练习2:猜年龄
Umi = 21
tag = True
while flog:
    inp_age = input("请输入年龄:").strip()
    if inp_age.isdigit():
        age = int(inp_age)
        if age > Umi:
            print('猜大啦')
        elif age < Umi:
            print('猜小啦')
        else:
            print('猜对了')
            tag = False
    else:
        print('请输入数字')

2.for循环语法

2.1什么是for循环?

  • 循环就是重复做某件事,for循环就是Python提供的第二种循环机制

2.2为何要有for循环?

  • 理论上for循环能做的事情,while循环都能做
  • 之所以要有for循环,是因为for循环在循环取值(遍历取值)比while循环更简洁

2.3如何用for循环?

基本使用之循环取值语法:
for 变量名 in 可迭代对象: #可迭代对象可以是:列表、字典、字符串、元组、集合
    代码1
    代码2
    代码3

案例1:列表循环取值

# 简单版
l = ['xxq','qwe','asd']
for i in l:
    print(i)
    
xxq
qwe
asd

# 复杂版
l = ['xxq','qwe','asd']
i = 0
while i < 3:
    print(l[i])
    i += 1
    
xxq
qwe
asd

案例2:字典循环取值

# 简单版
dic = {'name':'xxq','age':18,'gender':'male'}
for i in dic:
    print(i,dic[i])
    
name xxq
age 18
gender male
# 复杂版
# while循环可以遍历字典,但是太麻烦了

案例3:字符串循环取值

# 简单版
msg = 'my name'
for i in msg:
    print(i)
    
m
y
 
n
a
m
e

总结for循环与while循环的异同

  • 相同之处:都是循环,for循环能做的事,while循环都能做
  • 不同之处:while循环称之为“条件循环”,循环次数取决于条件何时变为假
    for循环称之为“取值循环”,循环次数取决in后包含的值的个数
for i in [1,2,3]:
    print('=====>')
    print('666666')
    
=====>
666666
=====>
666666
=====>
666666

for循环控制循环次数:range()

  • in后直接放一个数据类型来控制循环次数有局限性:当循环次数过多时,数据类型包含值的格式需要增加
  • 特性:顾头不顾尾
>>> range(10)       # 顾头不顾尾,下标是0-9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,9)      # 从一开始1-9,取不到9,所以是1-8
[1, 2, 3, 4, 5, 6, 7, 8]
>>> range(1,9,1)    # 从一开始1-9,取不到9,步长是1,所以是1-8
[1, 2, 3, 4, 5, 6, 7, 8]
>>> range(1,9,2)    # 从一开始1-9,取不到9,步长是2,所以是1,3,5,7
[1, 3, 5, 7]
>>>

for i in range(5):
    print("*******")
    
*******
*******
*******
*******
*******

案例应用

for + break 的连用,和 while 循环一样

for + else 的连用,和 while 循环一样

username = 'xxq'
password = '123'
count=0

for i in range(3):
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')

    if inp_name == username and inp_pwd == password:
        print('登录成功')
        break
    else:
        print('帐号或密码错误,请重试')
else:
    print('输错3次,退出程序')

for循环嵌套:外层循环 循环一次,内层循环 需要完整的循环完毕

for i in range(3):
    print('外层循环——>',i)
    for j in range(5):
        print('内层循环——>', j)
        
外层循环——> 0
内层循环——> 0
内层循环——> 1
内层循环——> 2
内层循环——> 3
内层循环——> 4
外层循环——> 1
内层循环——> 0
内层循环——> 1
内层循环——> 2
内层循环——> 3
内层循环——> 4
外层循环——> 2
内层循环——> 0
内层循环——> 1
内层循环——> 2
内层循环——> 3
内层循环——> 4

for + continue

for i in range(6):  #0 1 2 3 4 5
    if i == 4:
        continue    #直接跳过4
    print(i)
0
1
2
3
5

补充:终止for循环只有break一种方案

print('hello %s' % 'eogn')
print('hello' ,'world', 'eogn')

hello eogn
hello world eogn
print('hello
')
print('world')

hello

world
print('hello
',end='')
print('world')

hello
world
print('hello',end='*')
print('world',end='*')

hello*world*
原文地址:https://www.cnblogs.com/qujiu/p/12451889.html