python基礎-12流程控制之while循環

while

循環就是一個重複的過程,咱們人須要重複幹一個活,那麼計算機也須要重複幹一個活。
while循環又稱爲條件循環。
語法列子python

while 條件
    code 1
    code 2
    code 3
    ...

while True:
    print('*1'*100)
    print('*2'*100)

ATM列子code

# 實現ATM的輸入密碼從新輸入的功能
while True:
    user_db = 'nash'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
    else:
        print('username or password error')

ps:上述代碼雖然實現了功能,可是用戶密碼輸對了,他也會繼續輸入。input


while + break

break的意思是終止掉當前層的循環,執行其餘代碼。cmd

while True:
    user_db = 'nash'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        break
    else:
        print('username or password error')

print('退出了while循環')
# 輸出結果password: 123
# username: nash
# password: 123
# login successful
# 退出了while循環


while + continue

continue的意思是終止本次循環,直接進入下一次循環
用法列子class

n = 1
while n < 10:
    if n == 8:
        # n += 1  # 若是註釋這一行,則會進入死循環
        continue
    print(n)
    n += 1

ps:continue不能加在循環體的最後一步執行的代碼,由於代碼加上去毫無心義,以下所示的continue所在的位置就是毫無心義的。ps:注意是最後一步執行的代碼,而不是最後一行。循環


while 循環的嵌套

ATM密碼輸入成功還須要進行一系列的命令操做,好比取款,好比轉帳。而且在執行功能結束後會退出命令操做的功能,即在功能出執行輸入q會退出輸出功能的while循環而且退出ATM程序。語法

# 退出內層循環的while循環嵌套
while True:
    user_db = 'nash'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while True:
            cmd = input('請輸入你須要的命令:')
            if cmd == 'q':
                break
            print(f'{cmd} 功能執行')
    else:
        print('username or password error')

print('退出了while循環')
# 輸出結果password: 123
# username: nash
# password: 123
# login successful
# 退出了while循環


tag控制循環退出

# tag控制循環退出
tag = True
while tag:
    user_db = 'nash'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while tag:
            cmd = input('請輸入你須要的命令:')
            if cmd == 'q':
                tag = False
            print(f'{cmd} 功能執行')
    else:
        print('username or password error')

print('退出了while循環')


# username: nash
# password: 123
# login successful
# 請輸入你須要的命令:q
# q 功能執行
# 退出了while循環


while + else

while+else:else會在while沒有被break時纔會執行else中的代碼程序

# while+else
n = 1
while n < 3:
    print(n)
    n += 1
else:
    print('else會在while沒有被break時纔會執行else中的代碼')
    
# 1
# 2
# else會在while沒有被break時纔會執行else中的代碼
相關文章
相關標籤/搜索