python的while循环

# 1、嵌套多层循环,需求是想一次性终止所有层的循环,推荐使用方式二# 方式一:
while 条件1:
    while 条件2:
        while 条件3:
            break
        break
    break
# 方式二:
tag=True
while tag:
    while tag:
        while tag:
            tag=False
# 2、循环嵌套小案例# 需求一:输错账号密码,重新输入重新验证# 需求二:输错3次,退出程序# 需求三:输对账号密码,登录成功之后,可以循环接收用户输入的命令并执行
username = ‘egon‘
password = ‘123‘

count = 0

while count < 3:  # count=3
    # if count == 3:break

    inp_user = input(‘请输入你的用户名:‘)
    inp_pwd = input(‘请输入你的密码:‘)

    if inp_user == username and inp_pwd == password:
        print(‘登录成功‘)

        while True:
            cmd = input(‘请输入你的命令(输入q退出): ‘)
            if cmd == ‘q‘:
                break
            print(‘%s 正在执行‘ % cmd)

        break
    else:
        print(‘输入的账号或密码错误‘)
        count += 1  # count=3


username = ‘egon‘
password = ‘123‘

count = 0
tag=True

while tag:
    if count == 3:break

    inp_user = input(‘请输入你的用户名:‘)
    inp_pwd = input(‘请输入你的密码:‘)

    if inp_user == username and inp_pwd == password:
        print(‘登录成功‘)
        while tag:
            cmd = input(‘请输入你的命令(输入q退出): ‘)
            if cmd == ‘q‘:
                # 退出程序
                tag=False
            else:
                print(‘%s 正在执行‘ % cmd)

    else:
        print(‘输入的账号或密码错误‘)
        count += 1  # count=3
# 3、while+continue:continue会结束本次循环,直接进入下一次循环
count = 1

while count < 6:  # 5 < 6
    if count == 4:  # 4==4
        count += 1 # count=5
        continue  # 强调:在continue之后不应该写与其同级的代码,因为为将无法运行

    print(count)  #
    count += 1  # 6
#4、while+else
count=1
while count < 6:
    # if count == 3:break
    if count == 4:
        count+=1
        continue
    print(count)
    count+=1
else:
    #else对应的子代码块会在while循环结束后,并且不是被break强行结束的情况下执行
    print(‘====end====‘)

相关推荐