流程控制之 while 循环

流程控制之while

while 条件循环语句

  • 循环就是一个重复的过程
while 条件:
    代码1
    代码2
    ...
username = 'jin'
password = '1314'
while True:
    inp_username = input('请输入你的用户名>>>:')
    inp_password = input('请输入你的密码>>>:')
    if inp_username == username and inp_password == password:
        print('登录成功')
    else:
        print('登录失败')
# while True 一直循环登录,无论你输入的信息是对还是错.
  • 死循环
while True:
    print(1+1)
# 无止境的一直循环下去.

while...break

  • break 终止当前的循环
while True:
    print('结束循环')
    break
    代码2
    ...
username = 'jin'
password = '1314'
while True:
    inp_username = input('请输入你的用户名>>>:')
    inp_password = input('请输入你的密码>>>:')
    if inp_username == username and inp_password == password:
        print('登录成功')
        break  # 当用户输入正确的时候呢, break 会结束循环.
    else:
        print('登录失败')

while contine

  • contine 终止本次循环,进入下一次循环
count = 0
while count < 3:
    if count == 1:
        contine
    print(count)
    count += 1

while else

  • while 循环在没有被 break 时,才会执行 else 中的代码.
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print('正常循环完后打印')

while 循环的嵌套

username = 'jin'
password = '123'

while True:
    username = 'jin'
    password = '123'
    inp_uaername = input('请输入你的用户名或输入"q"退出>>>:')
    inp_password = input('请输入你的密码或输入"q"退出>>>:')
    if inp_uaername == 'q' or inp_password == 'q':
        break
    if inp_uaername == 'jin' and inp_password == password:
        print('登录成功')
        while True:
            cmd = input('请输入你的指令>>>:')
            if cmd == 'q'
                break
            print('%s功能执行'%(cmd))
        break
    else:
        print('登录失败!')
print('退出循环')

猜你喜欢

转载自www.cnblogs.com/jincoco/p/11121702.html
今日推荐