Python入门——循环

while循环

  • while循环的基本语法
'''
while 条件:
    子代码1
    子代码2
    子代码3
'''
count=0
while count < 5: # 5 < 5
    print(count)
    count+=1 # count=5
print('======end=====')
'''
0
1
2
3
4
======end=====
'''
  • 死循环:循环永远不终止,称之为死循环
# count=0
# while count < 5:
#     print(count)

# while True:
#     print('ok')


# while 1:
#     print('ok')

# 不要出现死循环
# while True:
#     1+1
  • 循环的应用
    需求一:输错密码,重新输入重新验证
# 方式一:
# username='egon'
# password='123'
#
# while True:
#     inp_user=input('请输入你的用户名:')
#     inp_pwd=input('请输入你的密码:')
#
#     if inp_user == username and inp_pwd == password:
#         print('登录成功')
#         break
#     else:
#         print('输入的账号或密码错误')
#
#     print('======end======')


# 方式二
username='egon'
password='123'

tag=True
while tag:
    inp_user=input('请输入你的用户名:')
    inp_pwd=input('请输入你的密码:')

    if inp_user == username and inp_pwd == password:
        print('登录成功')
        tag=False
    else:
        print('输入的账号或密码错误')

    print('======end======')
  • 如何终止循环
# 方式一:把条件改成假,必须等到下一次循环判断条件时循环才会结束
tag=True
while tag: # tag=False
    print('ok')
    tag=False
    print('hahahahhahahahahahaha')



# 方式二:break,放到当前循环的循环体中,一旦运行到break则立刻终止本层循环,不会进行下一次循环的判断
# while True:
#     print('ok')
#     break
#     print('hahahahhahahahahahaha')
  • 嵌套多层循环,需求是想一次性终止所有层的循环,(推荐使用方式二)
# 方式一:
# while 条件1:
#     while 条件2:
#         while 条件3:
#             break
#         break
#     break

# 方式二:
tag=True
while tag:
    while tag:
        while tag:
            tag=False

猜你喜欢

转载自www.cnblogs.com/guanxiying/p/12345041.html
今日推荐