While True用法小例子

yuqiong11發表於2020-12-09
d = {'a': '111', 'b': '123'}

count_user = 5  # max_input times is 5
while True:
    if count_user:
        name = input('請輸入您的使用者名稱:')
        if name in d:
            break
        else:
            count_user -= 1
            print('您輸入的使用者名稱不存在,請重新輸入')
            continue
    else:
        print('Wrong username input for 5 times, please try again tomorrow')
        break

count_password = 5  # max_input times is 5
while True and count_user:
    if count_password:
        password = input('請輸入您的密碼:')
        if d[name] == password:
            print('進入系統')
            break
        else:
            count_password -= 1
            print('您輸入的密碼不正確,請重新輸入')
            continue
    else:
        print('Wrong password input for 5 times, please try again tomorrow')
        break

程式很簡單,先輸入使用者名稱,輸對就break跳出while迴圈,進入輸密碼的迴圈,輸錯就迴圈重新輸入,總共5次機會,全錯程式結束。輸入密碼同理。

While True實際上就是無限迴圈,所以必須迴圈內滿足條件必須要break。

本文參考了 https://blog.csdn.net/geerniya/article/details/77524173

相關文章