python中的while


while循環

循環就是一個重復的過程,不斷的重復。while循環又稱條件循環

while 條件:
    code 1
    code 2
    code 3
    ...
##實現ATM的輸入密碼重新輸入的功能
while True:
    user_db='lzs'
    pwd_db='123'
    inp_user=input('請輸入用戶名')
    inp_pwd=input('請輸入密碼')
    if inp_user==user_db and pwd_db==inp_pwd:
        print('登陸成功')
     else:
        print('用戶名或者密碼不正確')
while+break

break的意思是終止掉當層的循環,執行其他代碼

while True:
    print('lzs')
    print(186)
    break
    print(136)
   ##1  2   

循環的目的是為了讓計算機和人一樣工作,循環處理事情,break適用於在某種特定循環下跳出循環

while+continue
n=1
while n<10:
    if n==8:
        contine
    print(n)
    n+=1

continue不能加在循環體的最后一步執行的代碼,因為代碼加上去毫無意義ps:注意最后一步執行的代碼,而不是最后一行

while循環的嵌套

ATM密碼輸入成功還需要進行一系列的命令操作,比如取款,比如轉賬。並且在執行功能結束后會退出命令操作的功能,即在功能出執行輸入q會退出輸出功能的while循環並且退出ATM程序

##退出內層循環的while循環嵌套
while True:
    user_db='lzs'
    pwd_db='1234'
    inp_user=input('請輸入你的用戶名')
    inp_pwd=input('請輸入你的密碼')
    if inp_user==user_db and pwd_db==inp_pwd:
        print('登陸成功')
        while True:
            cmd=input('請輸入你需要的命令:')
            if cmd=='q':
                break
                print(f'{cmd}功能執行')
            else:
                print('用戶名或者密碼錯誤')
print('退出了while循環')
##退出雙層循環嵌套
while True:
    user_db='lzs'
    pwd_db='1234'
    inp_user=input("請輸入用戶名")
    inp_pwd=input('請輸入密碼')
    if inp_user==user_db and pwd_db==inp_pwd:
        print("登陸成功")
        while True:
            cmd=input('請輸入你需要的命令')
            if cmd=='q':
                break
                print(f'{cmd}功能執行)
         break
     else:
          print('用戶名或者密碼錯誤')                                 
print('退出了while循環')                     
while+else

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

n=1
while n<3:
    print(n)
    n+=1
else:
    print('else會在while沒有被break時才會執行else中的代碼')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM