1. while循环:条件循环
I: 基本语法
while 条件:
代码1
代码2
代码3
...

示范:

name_of_bk = 'egon'
pwd_of_bk = '123'

tag = True#定义条件为真
while tag:
    inp_name = input('your name>>: ')#输入姓名
    inp_pwd = input('your password>>: ')#输入密码
    if inp_name == name_of_bk and inp_pwd == pwd_of_bk: #判断是否姓名,密码一致
        print('login successful')
        tag = False#改变条件,终止循环
    else:
        print('username or password error')

    print('other code...')

  

2: while+break:break代表结束本层循环
示范:
while True:
print(1)
break
print(2)
print(3)
name_of_bk = 'egon'
pwd_of_bk = '123'

while True:
    inp_name = input('your name>>: ')
    inp_pwd = input('your password>>: ')
    if inp_name == name_of_bk and inp_pwd == pwd_of_bk:
        print('login successful')
        break
    else:
        print('username or password error')

    print('other code......')
3: while + continue: continue代表结束本次循环,直接进入下一次
示范
count=1
while count < 6:
    if count == 3:
        count+=1
        continue
    print(count)
    count+=1

4:while + else
else的子代块只有在while循环没有被break打断的情况下才会执行

 count=0
 while True:
     if count == 10:
         break
     print(count)
     count+=1

 else:
     print("")
  

注意:

两个经典代码:

简单购物车

简单的购物程序:
name_of_bk='egon'
pwd_of_bk='123'

count=0
tag=True
while tag:
    if count == 3:
        print('输错的次数过多。。。')
        break
    inp_name=input('your name>>: ')
    inp_pwd=input('your password>>: ')
    if inp_name == name_of_bk and inp_pwd == pwd_of_bk:
        print('login successful')
        while tag:
            print("""
            0 退出
            1 购物
            2 支付
            3 查看购物
            """)
            cmd=input('>>>: ')
            if cmd == '0':
                tag=False
                continue
            if cmd == '1':
                print('购物。。。。。。。')
            elif cmd == '2':
                print('支付。。。。。')
            elif cmd == '3':
                print('查看购物车')
            else:
                print('输入错误的指令')
    else:
        print('username or password error')
        count+=1 #count=3 输错3次
View Code

 

输错三次退出 

 1 输错三次退出
 2  name_of_bk = 'egon'
 3  pwd_of_bk = '123'
 4 
 5  count = 0
 6  while True:
 7      if count == 3:
 8          print('输错的次数过多。。。')
 9          break
10      inp_name = input('your name>>: ')
11      inp_pwd = input('your password>>: ')
12      if inp_name == name_of_bk and inp_pwd == pwd_of_bk:
13          print('login successful')
14          break
15      else:
16          print('username or password error')
17          count += 1  # count=3 输错3次
View Code

句型:循环嵌套

 tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False
复制代码

  


posted on 2018-11-22 16:22  飞花飘絮  阅读(173)  评论(0编辑  收藏  举报