二 while循環

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("")
  

注意:python

兩個經典代碼:ide

簡單購物車spa

簡單的購物程序:
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

 

輸錯三次退出 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

句型:循環嵌套blog

 tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False
複製代碼
相關文章
相關標籤/搜索