python07——while循环

一、什么是循环

循环就是重复做某件事

二、为何要重复循环

为了让计算机像人一样去重复做某件事

三、如何用循环

while循环又称条件循环

3.1while循环基本语法

while 条件:
    代码1
    代码2
    代码3
count = 0
while count < 6:
    print(count)
    count +=1
    
# 0
# 1
# 2
# 3
# 4
# 5

3.2while循环的案例

案例一:输用户名与密码

username = "yoyo"
password = "123"

print('顶级代码....')
while True:
    inp_name=input("请输入用户名:")
    inp_pwd=input("请输入密码:")

    if inp_name == username and inp_pwd == password:
        print('login successful')
        break
    else:
        print('username or password error')
    print("====end====")
username = "yoyo"
password = "123"

tag = True
print('顶级代码....')
while True:
    inp_name=input("请输入用户名:")
    inp_pwd=input("请输入密码:")

    if inp_name == username and inp_pwd == password:
        print('login successful')
        tag = False
    else:
        print('username or password error')
    print("====end====")

3.3结束while循环的两种方式

方式一:把条件改成假,必须等到下一次循环判断条件时循环才会结束

tag=True
while tag:
  print("ok")
  tag=False
  print("哈哈哈哈哈哈哈")
  
# ok
# 哈哈哈哈哈哈哈

方式二:break,放到当前循环的循环体中,一旦运行到break则立刻终止本层循环,不会进行下一次循环的判断

while True:
  print("ok")
  break
  print("哈哈哈哈哈哈哈")
  
# ok

3.4循环嵌套

while 条件1:
    while 条件2:
        while 条件3:
            break
        break
    break

tag=True
while tag:
    while tag:
        while tag:
            tag=False

3.5 while+continue:终止本次循环,直接进入下一次

count=0
while count < 6:
    if count == 3:
        count +=1
        continue  # 注意:continue同级别之后一定不要写代码

    print(count)
    count +=1
    
    
#0
#1
#2
#4
#5

3.6 while+else

while count < 6:
    if count == 3:
        break
    print(count)
    count +=1
else:
		print("=====")     # 当while循环正常结束后才运行,break强制结束,所以不会运行
    
#0
#1
#2
#4
#5
count=0
while count < 4:
        print(count)
        count +=1
else:
    print("=====")   # while循环正常结束则运行else
    
#0
#1
#2
#3
#=====

3.7死循环

不要出现死循环

count=0
while count < 4:
    print(count)

while True:
    print('ok')


while 1:

    print('ok')
posted @ 2020-11-19 19:23  岳岳-  阅读(190)  评论(0编辑  收藏  举报